2017-08-27 103 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 
相關問題