Firebase наблюдает за новыми добавленными данными, даже когда функция не вызывается - PullRequest
1 голос
/ 27 мая 2019

У меня есть функция, которая наблюдает за данными из моей базы данных Firebase. Эти данные будут вставлены в массив, поэтому их можно отправить моему ViewViewttler контроллера tableview. Все данные будут правильно помещены в 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
    }

1 Ответ

1 голос
/ 27 мая 2019

Чтобы прослушать один раз, замените

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

на

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

или

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

для прослушивания добавленных потомков

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...