ale00 ale00 - 3 months ago 78
Swift Question

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.
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. But I can't return the value from the Firebase method because it's a void method...

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?

Answer

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