【问题标题】:Fetch new comments from firebase using a query使用查询从 firebase 获取新评论
【发布时间】:2021-09-04 17:26:00
【问题描述】:

我有一个在用户刷新页面时调用的 handleRefresh() 函数。当刷新发生时,已发布的新 cmets 会加载到 tableview 中。

我遇到的问题是,当用户刷新 tableview 中的数据时,我会加载两次,所以我得到了更新的 cmets,但有重复项,它再次重新加载了旧的 cmets。

我有点不知道如何解决这个问题。

这里是代码。

var CommentsQuery: DatabaseQuery {
    let postRef = Database.database().reference().child("posts")
    let postKey = keyFound
    let postCommentRef = postRef.child(postKey)
    let lastComment = self.comments.last
    var queryRef: DatabaseQuery
    
    if lastComment == nil {
        queryRef = postCommentRef.queryOrdered(byChild: "timestamp")
    } else {
        let lastTimestamp = lastComment!.createdAt.timeIntervalSince1970 * 1000
        queryRef = postCommentRef.queryOrdered(byChild: "timestamp").queryEnding(atValue: lastTimestamp)
    }
    return queryRef
}


@objc func handleRefresh() {

CommentsQuery.queryLimited(toLast: 20).observeSingleEvent(of: .value) { snapshot in
    
    var tempComments = [Comments]()
    let commentsSnap = snapshot.childSnapshot(forPath: "comments")
    let allComments = commentsSnap.children.allObjects as! [DataSnapshot]
    
    for commentSnap in allComments {
        let degree = commentSnap.childSnapshot(forPath: "reply degree").value as? String ?? ""
        let name = commentSnap.childSnapshot(forPath: "reply name").value as? String ?? ""
        let text = commentSnap.childSnapshot(forPath: "reply text").value as? String ?? ""
        let university = commentSnap.childSnapshot(forPath: "reply university").value as? String ?? ""
        let photoURL = commentSnap.childSnapshot(forPath: "reply url").value as? String ?? ""
        let url = URL(string: photoURL)
        let timestamp = commentSnap.childSnapshot(forPath: "timestamp").value as? Double
        let lastComment = self.comments.last
         
        if snapshot.key == lastComment?.id {
            
            let newComments = Comments(id: snapshot.key, fullname: name, commentText: text, university: university, degree: degree, photoURL: photoURL, url: url!, timestamp: timestamp!)
            
            tempComments.insert(newComments, at: 0)
            print("fetchRefresh")
        }
    }
    self.comments.insert(contentsOf: tempComments, at: 0)
    self.fetchingMore = false
    self.refreshControl.endRefreshing()
    self.tableView.reloadData()
}
  }

【问题讨论】:

    标签: swift firebase firebase-realtime-database tableview


    【解决方案1】:

    如果self.comments.last 在页面重新加载时仍然存在,那么问题似乎在于您在此处使用queryEnding(atValue:

    queryRef = postCommentRef.queryOrdered(byChild: "timestamp").queryEnding(atValue: lastTimestamp)
    

    由于时间戳值是递增的(值越高越新),您希望节点的时间戳高于最新值,您可以使用 queryStarting(atValue: 而不是 queryEnding(atValue:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      相关资源
      最近更新 更多