我该怎么做queryOrdered(bychild)呢?

时间:2017-08-27 21:31:56

标签: ios firebase swift3 firebase-realtime-database

我已经设置了我的firebase,如图所示,现在我想通过比较每个帖子的时间戳来为我的帖子添加新帖子,我已经写了下面的代码

func getRecentPosts(start timestamp: Int? = nil, limit: UInt, completionHandler: @escaping (([Post]) -> Void)){

    let POST_DB_REF: DatabaseReference = Database.database().reference().child("posts")
    var allPosts = POST_DB_REF.queryOrdered(byChild: "timestamp")

    if let latestPostTimestamp = timestamp, latestPostTimestamp > 0 {
        //If the timestamp is specified, we will get the posts with timestamp newer than the given value
        allPosts = allPosts.queryStarting(atValue: latestPostTimestamp + 1, childKey: Post.PostInfoKey.timestamp).queryLimited(toLast: limit)
    } else {
        //Otherwise, we will just get the most recent posts
        allPosts = allPosts.queryLimited(toLast: limit)
    }

    //Call Firebase API to retrieve the latest records
    allPosts.observeSingleEvent(of: .value, with: { (snapshot) in
        var newPosts: [Post] = []
        for userPosts in snapshot.children.allObjects as! [DataSnapshot] {
            for eachPost in userPosts.children.allObjects as! [DataSnapshot] {
                let postInfo = eachPost.value as? [String:Any] ?? [:]
                if let post = Post(postId: eachPost.key, postInfo: postInfo) {
                    newPosts.append(post)
                }
            }
        }

        if newPosts.count > 0 {
            //Order in descending order (i.e. the latest post becomes the first post)
            newPosts.sort(by: {$0.timestamp > $1.timestamp})
        }
        completionHandler(newPosts)
    })
}

这是我的firebase配置。 FIREBASE 这适用于第一次运行,如果我发布一个新的Feed它没有得到更新,任何想法? 提前致谢。

1 个答案:

答案 0 :(得分:0)

当您使用allPosts.observeSingleEvent时,您将始终从本地Firebase缓存中获取值。如果您始终需要来自服务器的最新值,则必须使用allPosts.observe代替服务器上的值更改后立即触发事件。

另一种选择是禁用缓存:

Database.database().isPersistenceEnabled = false