I'm trying to check if a username has already been taken. To do this, when a user registers, their username is added to a separate node 'taken_usernames'

I've then written the function:

func isUserNameTaken(username: String) -> Bool {
    var available = true
    Database.database().reference().child("taken_usernames").child(username).observeSingleEvent(of: .value) { (snapshot) in
        if snapshot.exists() {
            SVProgressHUD.dismiss()
            self.showLoginError("Username Taken. Please Try Another")
            available = false
        }
    }
    return available
}

And when the register button is pressed, I've created a guard statement:

@objc func register() {
    guard isFormValid() else { return }
    guard isUserNameTaken(username: registerView.usernameTextField.text!) else { return }
...}

However, I get the alert saying the username is taken but the rest of the function runs anyway so a new user is created with a duplicate username. Any ideas to why this is happening?

0 Answers