按降序时间过滤时,向Firebase观察者添加新帖子

时间:2016-10-09 17:42:48

标签: ios swift firebase firebase-realtime-database

因此,我有一个用户将发布的Feed,并希望每个新提交都转到我的集合视图的顶部。我按照此处显示的UTC时间的负值,按降序时间对每个新帖子进行排序:How do you properly order data from Firebase chronologically

    "Posts" : {
      "-KHLOy5mOSq0SeB7GBXv" : {
           "timestamp" : "1476028495915",
           "descendStamp": "-1476028495915"
           "otherData": ""
       },
      "-KHLrapS0wbjqPP5ZSUY" : {
           "timestamp" : "1476028496102"
           "descendStamp" : "-1476028496102"
           "otherData": ""
       },

但是,添加的每个新实时帖子在最初加载时都会被置于底部。相信这是因为观察者只是异步加载新添加的孩子,而不是再次下载任何其他信息,这导致他忽略了我的

    .queryOrderedByChild("descendStamp")

离开并返回视图后,它会将最近添加的帖子正确组织到顶部。我是否需要客户端过滤才能实时获取这些新帖?或者,当新的帖子进入时,重新组织帖子顺序的最佳方法是什么?

    var posts = [PostModel]()

    let postQuery = ref.child("Posts").queryOrderedByChild("descendStamp")
        postQuery.observeEventType(.ChildAdded, withBlock: { (snap) in


            if snap.exists() {
                let postData = snap.value! as! [String: AnyObject]

                let post = PostModel()

                post.timestamp = postData["timestamp"] as? NSTimeInterval
                post.descendStamp = postData["descentStamp"] as? NSTimeInterval
                post.otherData = postData["otherData"] as? String

                self.posts.append(post)

                dispatch_async(dispatch_get_main_queue(), {
                    self.collectionView!.reloadData()
                })
            }

1 个答案:

答案 0 :(得分:0)

在更新tableView之前,只需对dataSource进行排序。

self.posts.sort(by: {$0.descendStamp > $1.descendStamp})

您的代码看起来像这样: -

var posts = [PostModel]()

let postQuery = ref.child("Posts").queryOrderedByChild("descendStamp")
    postQuery.observeEventType(.ChildAdded, withBlock: { (snap) in


        if snap.exists() {
            let postData = snap.value! as! [String: AnyObject]

            let post = PostModel()

            post.timestamp = postData["timestamp"] as? NSTimeInterval
            post.descendStamp = postData["descentStamp"] as? NSTimeInterval
            post.otherData = postData["otherData"] as? String

            self.posts.append(post)
            self.posts.sort(by: {$0.descendStamp > $1.descendStamp})

            dispatch_async(dispatch_get_main_queue(), {
                self.posts.sort(by: {$0.descendStamp > $1.descendStamp})
                self.collectionView!.reloadData()
            })
        }