2017-08-27 99 views
1

我已经建立了我的火力点在图片中,现在我想通过比较每个岗位时间戳只新帖养活我的帖子,我已经写了下面我该怎么做queryOrdered(bychild)呢?

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 这与第一次运行,然后如果我发布一个新的饲料它没有得到更新,任何想法? 在此先感谢。

+0

如何getRecentPosts被称为?错误可能是这个方法没有被调用? –

+0

是的,我在我的FeedTableViewController中调用此方法添加新帖子。 –

+0

实际上,在ViewDidLoad和每次发布内容时都会调用两种方法。 –

回答

0

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

另一种方法是禁用缓存:

Database.database().isPersistenceEnabled = false 
相关问题