-->

如何在火力地堡数据进行排序?(How to sort data in Firebase?)

2019-10-16 12:12发布

我现在可以通过时间的帖子和用户进行排序。

我的数据结构,看起来像这样:

posts
 -postId
     imageRatio: 
     imageUrl: 
     postText: 
     postTime: 
     uId:
users
 -UserId
    email: 
    profileImageURL: 
    radius: 
    uid: 
    username: 
    username_lowercase: 

UPDATE

现在,我创建了所有提交的数据为用户和发布一个新类:

class UserPostModel {
    var post: PostModel?
    var user: UserModel?

    init(post: PostModel, user: UserModel) {
        self.post = post
        self.user = user
    }
}

我的帖子阵列宣言:

var postArray = [UserPostModel]()

在这里,林加载DATAS到新类:

self.observeRadius(completion: { (radius) in
                let currentRadius = radius
            // Üperprüfe, welche Posts im Umkreis erstellt wurden
                let circleQuery = geoRef.query(at: location!, withRadius: Double(currentRadius)!)

            circleQuery.observe(.keyEntered, with: { (postIds, location) in

                self.observePost(withPostId: postIds, completion: { (posts) in
                    guard let userUid = posts.uid else { return }
                    self.observeUser(uid: userUid, completion: { (users) in
                        let postArray = UserPostModel(post: posts, user: users)
                        self.postArray.append(postArray)
                        print(postArray.post!.postText!, postArray.user!.username!)
                        self.postArray.sort(by: {$0.post!.secondsFrom1970! > $1.post!.secondsFrom1970!})

                    })
                })

在这里,我加载DATAS到表视图细胞:

    extension DiscoveryViewController: UITableViewDataSource {
    // wie viele Zellen
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print(postArray.count)
        return postArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DiscoveryCollectionViewCell", for: indexPath) as! DiscoveryCollectionViewCell

        cell.user = postArray[indexPath.row]
        cell.post = postArray[indexPath.row]
        //cell.delegate = self

        return cell
    }
}

在此先感谢您的帮助!

Answer 1:

有很多的代码中的问题,有时候,越简单越好。 因此,让我们一起来Post类,加载的帖子,得到了相关的用户名,并将其存储在数组中。 然后,当完成,整理和打印时间倒序排列的职位。

一类担任此职的数据和用户名

class PostClass {
    var post = ""
    var timestamp: Int! //using an int for simplicity in this answer
    var user_name = ""

    init(aPost: String, aUserName: String, aTimestamp: Int) {
        self.post = aPost
        self.user_name = aUserName
        self.timestamp = aTimestamp
    }
}

需要注意的是,如果我们希望有同时拥有数据后,我们可以做到这一点的用户数据

class PostUserClass {
   var post: PostClass()
   var user: UserClass()
}

但我们简单说明这个答案。

然后一个数组来存储所述柱

var postArray = [PostClass]()

最后的代码加载在所有的职位,(在一个完整的例子或用户对象)获取相关的用户名。

let postsRef = self.ref.child("posts")
let usersRef = self.ref.child("users")
postsRef.observeSingleEvent(of: .value, with: { snapshot in
    let lastSnapIndex = snapshot.childrenCount
    var index = 0
    for child in snapshot.children {
        let childSnap = child as! DataSnapshot
        let uid = childSnap.childSnapshot(forPath: "uid").value as! String
        let post = childSnap.childSnapshot(forPath: "post").value as! String
        let timestamp = childSnap.childSnapshot(forPath: "timestamp").value as! Int
        let thisUserRef = usersRef.child(uid)

        thisUserRef.observeSingleEvent(of: .value, with: { userSnap in
            index += 1
            //for simplicity, I am grabbing only the user name from the user
            //  data. You could just as easily create a user object and
            //  populate it with user data and store that in PostClass
            //  that would tie a user to a post as in the PostUserClass shown above
            let userName = userSnap.childSnapshot(forPath: "Name").value as! String
            let aPost = PostClass(aPost: post, aUserName: userName, aTimestamp: timestamp)
            self.postArray.append(aPost) //or use self.postUserArray to store
                                         //  PostUserClass objects in an array.
            if index == lastSnapIndex {
                self.sortArrayAndDisplay() //or reload your tableView
            }
        })
    }
})

然后小功能进行排序,并打印到控制台

func sortArrayAndDisplay() {
    self.postArray.sort(by: {$0.timestamp > $1.timestamp})

    for post in postArray {
        print(post.user_name, post.post, post.timestamp)
    }
}

需要注意的是火力地堡是异步的排序/打印之前,我们需要知道我们正在做加载在所有数据。 这是通过lastSnapIndex和索引处理。 该指数只增加一次为每个用户加载,当所有的职位和用户都被装入我们对其进行分类和打印的数据是否完整。

这个例子避免了杂乱的回调和可能的问题是导致问题的完成处理 - 这段代码是嫌疑人,或许应该是由于火力地堡的异步性是可以避免的; 排序函数将所有的用户都加载之前被称为好。

UserApi.shared.observeUserToPost(uid: userUid) { (user) in
    self.postUser.append(user)
}
self.postUser.sort(by: {$0.postDate! > $1.postDate!})

*请添加错误检查。



文章来源: How to sort data in Firebase?