【问题标题】:Firebase observe new added data even when the function isn't called即使未调用该函数,Firebase 也会观察新添加的数据
【发布时间】:2019-05-26 22:21:19
【问题描述】:

我有一个函数可以观察我的 Firebase 数据库中的数据。该数据将被插入到一个数组中,因此可以发送到我的 tableviewcell Viewcontroller。所有数据都将正确放置在 tabelviewcell 中,但是当我更新 Firebase 数据库时出现问题。每次我更改数据库中的值时,即使未调用我的函数,它也会立即更新我的 tableView。我不确定我做错了什么以及如何防止这种情况。

这是我的功能观察:

Database.database().reference().child("posts").child("\(postId)").child("comments").observe(.value, with: { snapshot in
   if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
     for snap in snapshots {
       if let postDict = snap.value as? Dictionary<String, AnyObject> {
          let key = snap.key
          let post = Comment.transformComment(dict: postDict)
          self.comments.insert(post, at: 0)
          self.tableView.reloadData()
       }
     }
   }
})

数组:

var comments: [Comment] = []

extension Comment {
    static func transformComment(dict: [String: Any]) -> Comment {
        let comment = Comment()
        comment.commentText = dict["commentText"] as? String
        comment.uid = dict["uid"] as? String
        comment.timestamp = dict["timestamp"] as? Int
        comment.likeCount = dict["likeCount"] as? Int
        comment.childByAutoId = dict["childByAutoId"] as? String
        comment.id = dict["postId"] as? String
        return comment
    }
}

Tablevieww 函数:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if comments.count == 0 {
            self.tableView.setEmptyMessage("No comments yet!")
        } else {
            self.tableView.restore()
        }
        return comments.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Comment", for: indexPath) as! CommentTableViewCell
        let comment = comments[indexPath.row]
        cell.comment = comment
        cell.delegate = self

        return cell
    }

【问题讨论】:

    标签: swift uitableview firebase-realtime-database


    【解决方案1】:

    只听一次替换

    .child("comments").observe(.value, with: { snapshot in
    

    .child("comments").observeSingleEvent(of: .value) { snapshot in
    

    或者

    .child("comments").observe(.childChanged) { snapshot  in
    

    收听添加的孩子

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 2019-06-16
      相关资源
      最近更新 更多