How do I check if a key exists in Firebase? I have seen this link here, but it's for Firebase 3, and it doesn't work for my situation. So for my case, I want to check to see if a username exists, and if it does, then don't register a user, but if it doesn't then register. I have something along the lines of this:
let usersDB = Database.database().reference().child("Users")
var taken = false
usersDB.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild(username) {
taken = true
self.errorLabel.text = "Username already taken."
}
})
if !taken {
// Email registration
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
print(error!.localizedDescription)
self.errorLabel.text = error!.localizedDescription
} else {
// Allows for username log in
usersDB.child(username).setValue(["email" : user?.email])
self.performSegue(withIdentifier: "goToGroups", sender: self)
}
})
}
The observeSingleEvent
is what the previous similar post's solution was, but it only runs after I add a child on this line usersDB.child(username).setValue(["email" : user?.email])
, it never runs before. Is there any other way to do this?