I'm trying to understand where i may be going wrong with the following code. I have tried to look up a way to check if the users collection contains a string within one of it's documents within a username field.
Structure looks something like this
#users(collection)
#userID(document)
#name:String
#email:String
#username:String
#userID(document)
#name:String
#email:String
#username:String
What i am trying to check is if within users, and within any document, does the string exist in the username field. Found a possible solution to this question (among others) here by calling a function to query for the username.
I created the function in an extension:
extension UITextField {
func checkUsername(username: String, completion: @escaping(Bool) -> Void) {
let usernameRef = Database.database().reference()
usernameRef.child("users").queryOrdered(byChild: "username").queryEqual(toValue: username).observeSingleEvent(of: DataEventType.value, with: { (snapshot: DataSnapshot) in
if snapshot.exists() {
completion(true)
}
else {
completion(false)
}
})
}
}
and called it on the text field within textFieldDidEndEditing so it can perform the check upon the user attempting to claim a username.
func textFieldDidEndEditing(_ textField: UITextField) {
if activeField == usernameField {
textField.checkUsername(username: usernameField.text!) { isExist in
if isExist {
print("Username exists")
} else {
print("Username does not exist")
}
}
}
}
However, this always returns 'Username does not exist' to the console, even when the username does exist.
There is currently 1 username within the database called test, so attempting to enter test should return 'Username exists' and entering testtwo should return 'Username does not exist'.
What can i be missing here? I am assuming its not querying the database correctly?