在我的 iOS 应用中,用户可以通过搜索唯一的用户名来添加 friend 。
用户在 textField 中键入用户名,我有一个 textFieldDidChange 通知,每次文本更改时都会触发该通知。
然后,在该方法中,我调用下面的 Firebase 方法来检查用户名是否存在。
func searchFor(_ username: String) {
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
return
}
let lowercaseUsername = username.lowercased()
let ref = FIRDatabase.database().reference()
ref.child(FirebaseDatabaseBranchNames.usernames.rawValue).child(lowercaseUsername).observeSingleEvent(of: .value, with: { [unowned self](snapshot) in
if snapshot.exists() {
if let usernameUid = snapshot.value as? String {
self.isUserAlreadyAFriend(ref, uid: uid, usernameUid: usernameUid)
}
} else {
// username doesn't exist
}
}, withCancel: nil)
}
如何在再次执行之前取消此方法?
最佳答案
当您附加一个监听器/观察器时,Firebase 会返回该观察器的句柄。您随后可以通过调用 ref.removeObserverWithHandle()
来删除监听器/观察器。 .
所以假设您最多需要一个观察者,您可以将引用和观察者句柄保存在您类的成员字段中,然后在 searchFor
方法中使用此代码:
if (self.searchHandle != nil) {
self.searchRef.removeObserverWithHandle(searchHandle)
}
self.searchRef = ref.child(FirebaseDatabaseBranchNames.usernames.rawValue).child(lowercaseUsername)
self.searchHandle = self.searchRef.observeSingleEvent(of: .value, with: { [unowned self](snapshot) in
if snapshot.exists() {
if let usernameUid = snapshot.value as? String {
self.isUserAlreadyAFriend(ref, uid: uid, usernameUid: usernameUid)
}
} else {
// username doesn't exist
}
}, withCancel: nil)
请注意,尽管如此,您不会保存数据传输,因为最有可能的结果是数据库客户端只是丢弃从服务器返回的数据。
关于ios - 如何取消 firebase 观察单个事件数据库调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42468892/