0

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?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Luke Roberts
  • 311
  • 1
  • 4
  • 15
  • observeSingleEvent is asynchronous and returns immediately. The callback you provide will be called some time later, after the results from the database are received. Because of this, your function is going to return true every time, before anything is known from the database. – Doug Stevenson Apr 13 '19 at 20:40
  • See my answer here for another explanation, and more links: https://stackoverflow.com/questions/44711443/issues-reading-data-from-firebase-database/44711964#44711964 – Frank van Puffelen Apr 14 '19 at 00:02

0 Answers0