func checkUsername(username: String) -> Bool {
var avalible = true
Database.database().reference().child("usernames").child(username).observeSingleEvent(of: .value, with: { snapshot in
if snapshot.exists() {
print("exists")
avalible = false
}
})
return available
}
I'm trying to check if a username exists.
I've already tried multiple things, but it seems like the function always returns before the completion handler even finishes and always gives the same output (true) even if the username is already taken.
Does somebody have an idea how to „wait“ for the completion handler first to finish before returning the „available“ variable?
An explanation with the answer would be excellent.
Thanks.
You cannot return something from an asynchronous task. Your code – with fixed typos – returns
trueeven before the database request has been started.Maybe there is a native async/await version of
observeSingleEventbut in any case you can use aContinuationAnd call it