我使用firebase数据库。我跟踪了this article但我不明白为什么在删除了handleUserMessagesAdded
可观测值之后,handleUserMessagesAdded
仍然有一个值,并且仍然观察是否有任何内容添加到数据库中。我也试过removeAllObservers
,但没有改变。我有什么遗漏吗?啊!
class ChatController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var rootRef: DatabaseReference!
var handleUserMessagesAdded: UInt!
override func viewDidLoad() {
super.viewDidLoad()
rootRef = Database.database().reference()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observeMessages()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
// Remove listener with handle
rootRef.removeObserver(withHandle: handleUserMessagesAdded)
}
deinit {
print("Deinit gets called after back button is clicked! ")
}
func observeMessages() {
guard let uid = Auth.auth().currentUser?.uid ,let toId = user?.id else {return}
handleUserMessagesAdded = rootRef.child("userMessages").child(uid).child(toId).observe(.childAdded, with: { [unowned self] (snapshot) in
let messageId = snapshot.key
// Make the message to be seen for this user
let childUpdates = ["/userMessages/\(uid)/\(toId)/\(messageId)": 1]
self.rootRef.updateChildValues(childUpdates)
self.rootRef.child("messages").child(messageId).observeSingleEvent(of: .value, with: { [unowned self] (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else {return}
print(dictionary)
// Reload CollectionView
}, withCancel: nil)
}, withCancel: nil)
}
}
最佳答案
您需要在注册的同一个引用上调用removeObserver(withHandle: ...)
。
所以:
rootRef.child("userMessages").child(uid).child(toId).removeObserver(withHandle: handleUserMessagesAdded)
关于swift - 使用FirebaseHandle删除Firebase观察者不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48590137/