[英]Return value from Firebase Database async method
I want to check if there is already a user with the chosen username in Firebase and I've created a function checkUsernameAlreadyTaken(username: String) -> Bool
that do this.我想检查 Firebase 中是否已经有一个具有所选用户名的用户,并且我创建了一个函数
checkUsernameAlreadyTaken(username: String) -> Bool
来执行此操作。 Here is the code pf the function:这是函数的代码:
func checkUsernameAlreadyTaken(username: String) -> Bool {
databaseRef.child("usernames").child("\(username)").observe(.value, with: { (snapshot) in
print(username)
if snapshot.exists() {
print("Snapshot exist")
self.alreadyTaken = true
}
})
if alreadyTaken == true {
print("Username already taken")
return false
}
else {
return true
}
}
The problem is that the method observe(_ eventType: FIRDataEventType, with block: (FIRDataSnapshot) -> Void) -> Uint
is an async method and so I can not use the strategy you can see above.问题是方法
observe(_ eventType: FIRDataEventType, with block: (FIRDataSnapshot) -> Void) -> Uint
是一个异步方法,所以我不能使用你在上面看到的策略。 But I can't return the value from the Firebase method because it's a void method...但我无法从 Firebase 方法返回值,因为它是一个 void 方法......
How can I solve this problem?我怎么解决这个问题?
One more thing.还有一件事。 How can I return false also if there is a connection error or no connection with the server?
如果连接错误或与服务器没有连接,我如何也返回 false?
You have to employ asynchronous completion handler yourself and verify if there is Internet connection:您必须自己使用异步完成处理程序并验证是否有 Internet 连接:
func checkUsernameAlreadyTaken(username: String, completionHandler: (Bool) -> ()) {
databaseRef.child("usernames").child("\(username)").observe(.value, with: { (snapshot) in
print(username)
if snapshot.exists() {
completionHandler(false)
} else {
let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")
connectedRef.observe(.value, with: { snapshot in
if let connected = snapshot.value as? Bool, connected {
completionHandler(true)
} else {
completionHandler(false)
// Show a popup with the description
let alert = UIAlertController(title: NSLocalizedString("No connection", comment: "Title Internet connection error"), message: NSLocalizedString("No internet connection, please go online", comment: "Internet connection error saving/retriving data in Firebase Database"), preferredStyle: .alert)
let defaultOkAction = UIAlertAction(title: NSLocalizedString("No internet connection, please go online", comment: "Internet connection error saving/retriving data in Firebase Database"), style: .default, handler: nil)
alert.addAction(defaultOkAction)
self.present(alert, animated: true, completion: nil)
}
})
}
})
}
Then you call your method with:然后你调用你的方法:
checkIfUserExists(username: text, completionHandler: { (value) in
// ...
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.