首页 > 解决方案 > 区分记录更改和 Firebase 中删除的数据

问题描述

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

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")
    }
})

标签: swiftfirebasefirebase-realtime-database

解决方案


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

// 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, .....)使用


推荐阅读