如何在Firebase中对数据进行排序?

时间:2018-12-01 12:37:34

标签: swift firebase sorting firebase-realtime-database

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

我的数据结构如下:

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

更新

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

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

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

我的帖子数组的声明:

var postArray = [UserPostModel]()

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

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

                    })
                })

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

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

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

问题中有很多代码,有时,越简单越好。因此,让我们采用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)
    }
}

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

此示例避免了混乱的回调和完成处理程序,这些回调和完成处理程序可能会导致问题出现-该段代码令人怀疑,由于Firebase的异步特性,应避免使用它们;在加载所有用户之前,sort函数将被很好地调用。

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

*请添加错误检查。