从Firebase数据库异步方法

时间:2016-08-19 11:58:07

标签: ios swift firebase firebase-realtime-database

我想检查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?

1 个答案:

答案 0 :(得分:3)

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