且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-19 19:04:45

您必须自己使用异步完成处理程序,并验证是否存在Internet连接:

You have to employ asynchronous completion handler yourself and verify if there is Internet connection:

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
    // ...
})