一尘不染

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

swift

我想检查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方法返回值,因为它是空方法…
如何解决此问题?

还有一件事。如果连接错误或与服务器之间没有连接,如何也返回false?


阅读 333

收藏
2020-07-07

共1个答案

一尘不染

您必须自己使用异步完成处理程序,并验证是否存在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
    // ...
})
2020-07-07