在Firebase中区分记录更改和数据删除

时间:2018-08-27 21:00:52

标签: swift firebase firebase-realtime-database

使用以下代码,我试图观察何时更改记录或何时删除记录。缺少快照似乎并不表示已删除。有什么办法可以将这两种情况分开?

FireRef.child("dataRecords").child(dataRecord).observe(.value, with: { (snapshot) in
    if snapshot.exists() {
        let snapshot = snapshot.value as! [String: AnyObject]
        print("record has been modified: \(snapshot)")
    } else {
        print("record has been deleted")
    }
})

1 个答案:

答案 0 :(得分:1)

如果我理解您的问题,则可以在Firebase documentation中找到答案。

// Listen for new comments in the Firebase database
    commentsRef.observe(.childAdded, with: { (snapshot) -> Void in
    self.comments.append(snapshot)
    self.tableView.insertRows(at: [IndexPath(row: self.comments.count-1, section: self.kSectionComments)], with: UITableViewRowAnimation.automatic)
})
// Listen for deleted comments in the Firebase database
    commentsRef.observe(.childRemoved, with: { (snapshot) -> Void in
    let index = self.indexOfMessage(snapshot)
    self.comments.remove(at: index)
    self.tableView.deleteRows(at: [IndexPath(row: index, section: self.kSectionComments)], with: UITableViewRowAnimation.automatic)
})

您也可以使用commentsRef.observe(.childChanged, .....)