从Firebase数据库异步方法返回值

我想检查Firebase中是否已经有用户选择了用户名,我创建了一个函数checkUsernameAlreadyTaken(username: String) -> Bool执行此操作。 这是函数的代码:

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

问题是方法observe(_ eventType: FIRDataEventType, with block: (FIRDataSnapshot) -> Void) -> Uint是一种异步方法,所以我不能使用你上面看到的策略。 但我不能从Firebase方法返回值,因为它是一个void方法…
我怎么解决这个问题?

还有一件事。 如果连接错误或与服务器没有连接,我怎么能返回false?

您必须自己使用异步完成处理程序并validation是否存在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) } }) } }) } 

然后用以下方法调用您的方法:

 checkIfUserExists(username: text, completionHandler: { (value) in // ... })