I have the following Firebase query where I check if a username already exists in a database. I would like to assign a boolean value (true) to a variable called usernameAlreadyExists. However, I need to access this variable with its new value outside of the closure. I read that I need to implement a completionHandler or a callback in order to do this. However, I don't know how to implement this in the Firebase query syntax :
var usernameAlreadyExists = false
FIRDatabase.database().reference().child("usernames").queryOrderedByValue().queryEqual(toValue: self.username.text).queryLimited(toFirst: 1).observe(.childAdded, with: { snapshot in
// Username unavailable, chose another one
self.invalidUsernameMsg.text = "This username already exists, please choose another one."
print(snapshot)
print(snapshot.value)
usernameAlreadyExists = true
})
print(usernameAlreadyExists)
print(usernameAlreadyExists) --> I want this line to print "true", but it prints "false" because the code above is executed asynchronously.
Any help is more than welcome. Thank you!