3

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?

Michael Hsu
  • 950
  • 1
  • 9
  • 25

1 Answers1

11

This looks like an issue with handling asynchronous calls. if !taken is very likely going to be checked before data is returned from observeSingleEvent because it's asynchronous, so the rest of the code will continue to run. One option is to move if !taken into the closure, like this:

    let usersDB = Database.database().reference().child("Users/\(username)")
    var taken = false

    usersDB.observeSingleEvent(of: .value, with: { (snapshot) in
        if snapshot.exists() {
            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)
                }
            })
        }
    })
Jen Person
  • 7,356
  • 22
  • 30