0

I'm trying to check if a user exists in my database but it always says "Success" no matter if the user exists or not. I don't really understand FireBase docs, they are pretty poor, can anyone help me and tell me why I get success everytime?

        if nickTextField.text != "" {

    let db = Database.database().reference()

        var userExistsSwitch = false
        db.child("Usernames").observe(.value, with: { (snapshot) in
            if snapshot.hasChild("\(self.nickTextField.text!)") {
                userExistsSwitch = true
                print("Username already exists!")
            }
        })

        db.child("Usernames").removeAllObservers()

        if !userExistsSwitch {
            print("Success!")
            db.child("Usernames").child(self.nickTextField.text!).setValue(self.nickTextField.text!)
        }

    }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
AndreiVataselu
  • 216
  • 2
  • 16

1 Answers1

0

Loading data from Firebase happens asynchronously. This means that your code that prints success runs before the data has actually loaded. The easiest way to see this is with a few well places log statements:

let db = Database.database().reference()
print("Before attaching observer");
db.child("Usernames").observe(.value, with: { (snapshot) in
    print("Data has loaded");
})
print("After attaching observer");

When you run this code, it prints:

Before attaching observer

After attaching observer

Data has loaded

There is no way to change this behavior. It is simply the way most of the modern web works.

This means that you'll have to put any code that requires the data into the completion handler, or call it from within the completion listener. An easy way to do this in your case:

let db = Database.database().reference()

var userExistsSwitch = false
db.child("Usernames").observe(.value, with: { (snapshot) in
    db.child("Usernames").removeAllObservers()
    if snapshot.hasChild("\(self.nickTextField.text!)") {
        userExistsSwitch = true
        print("Username already exists!")
    }
    if !userExistsSwitch {
        print("Success!")
        db.child("Usernames").child(self.nickTextField.text!).setValue(self.nickTextField.text!)
    }
})
Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you. Helped me a lot. The code you pasted tho is not working because it's checking if `userExistsSwich` is false inside the `snapshot.hasChild` method. I edited it – AndreiVataselu Nov 29 '17 at 08:22