如何在Firebase中对数据排序? [英] How to sort data in Firebase?

查看:96
本文介绍了如何在Firebase中对数据排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在可以按时间对帖子和用户进行排序.

I'm now able to sort posts and users by time.

我的数据结构如下:

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

更新

现在,我创建了一个新类,其中包含用户和帖子的所有数据:

Now, I created a new class with all datas for the user and the posts:

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

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

我的帖子数组的声明:

var postArray = [UserPostModel]()

在这里,我将数据加载到新类中:

Here, Im loading the datas into the new class:

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!})

                    })
                })

在这里,我正在将数据加载到表格视图单元格中:

Here I'm loading the datas into the table view cells:

    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
    }
}

提前感谢您的帮助!

推荐答案

问题中有很多代码,有时,越简单越好.因此,让我们采用Post类,加载帖子,获取关联的用户名并将其存储在数组中.然后,完成后,按相反​​的时间顺序对帖子进行排序和打印.

There's a lot of code in the question and sometimes, simpler is better. So let's take a Post class, load the posts, get the associated user name and store it in an array. Then when complete, sort and print the posts in reverse chronological order.

用于保存帖子数据和用户名的类

A class to hold the post data and the user name

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
    }
}

请注意,如果我们希望同时拥有发布数据和用户数据,我们可以这样做

Note that if we want to have have both post data and user data we could do this

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

但我们对此回答保持简单.

but we're keeping it simple for this answer.

然后使用数组存储帖子

var postArray = [PostClass]()

最后是要在所有帖子中加载的代码,获取关联的用户名(或完整示例中的用户对象).

and finally the code to load in all of the posts, get the associated user name (or user object in a full example).

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
            }
        })
    }
})

然后是用于排序并打印到控制台的小功能

and then the little function to sort and print to console

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

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

请注意,Firebase是异步的,因此在排序/打印之前,我们需要知道已完成所有数据的加载.这是通过lastSnapIndex和index处理的.只有在加载了每个用户之后,索引才会增加,并且在所有帖子和用户都加载完毕后,我们将在数据完成后进行排序和打印.

Note that Firebase is asynchronous so before sorting/printing we need to know we are done loading in all of the data. This is handled via the lastSnapIndex and index. The index is only incremented once each user is loaded and when all of the posts and users have been loaded we then sort and print as the data is complete.

此示例避免了可能引起问题的混乱的回调和完成处理程序-此段代码令人怀疑,并且由于Firebase的异步特性而应避免使用;在加载所有用户之前,sort函数将被很好地调用.

This example avoids messy callbacks and completion handlers which may be contributing to the issue in the question - this piece of code is suspect and probably should be avoided due to the asynchronous nature of Firebase; the sort function is going to be called well before all of the users are loaded.

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

*请添加错误检查.

这篇关于如何在Firebase中对数据排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆