我按照下面的函数使用users
单例类成功地在Firebase路径DataService
上读取和侦听了数据更改。
Firebase参考:
REF_USERS = DB_BASE.child("users")
函数附加/监听路径和转义:
func getUsers(handler: @escaping (_ name: String, _ discoverable: Bool) -> ()){
REF_USERS.observe(.value) { (snapshot) in
guard let usersSnapshot = snapshot.children.allObjects as? [DataSnapshot] else { return }
for user in usersSnapshot{
let name = user.childSnapshot(forPath: "name").value as! String
let discoverable = user.childSnapshot(forPath: "discoverable").value as! Bool
handler (name, discoverable)
}
}
}
我正在DiscoverVC
中使用上述功能,
DataService.run.getUsers { (name, discoverable) in
print("name: \(name), discoverable: \(discoverable)")
}
如何在DiscoverVC
函数中从viewWillDisappear
中删除观察者?
我知道我需要在DatabaseHandle
调用中传递一个removeObserver
,如何构建该句柄?
override func viewWillDisappear(_ animated: Bool) {
DataService.run.REF_USERS.removeObserver(withHandle: <#T##UInt#>)
}
答案 0 :(得分:1)
根据Firebase documentation on detaching listeners:
将回调块添加到引用时,将返回
FIRDatabaseHandle
。这些句柄可用于删除回调块。
所以在您的情况下:
handle = REF_USERS.observe(.value) { (snapshot) in
...
}
然后在您的viewWillDisappear
中:
override func viewWillDisappear(_ animated: Bool) {
DataService.run.REF_USERS.removeObserver(withHandle: handle)
}