简体   繁体   中英

Checking to see if username exists in firebase DB.

I am trying to get a username from the user via @IBAction from the UI.

My goal is to check if the username already exists in Firebase. If it does not exists, then register it. If it does exist, I would like to do some other stuff.

Here is my code.

@IBAction func enterUsername(){

    let enteredUsername = usernameText!.text!
    let namesRef = ref.childByAppendingPath("/usernames/\(enteredUsername)")

    namesRef.observeEventType(.Value, withBlock: {
        snap in

        if (snap.value is NSNull){
            let userNameAndUUID = ["Username" : enteredUsername, "UUID" : self.appDelegate.UUID]
            namesRef.setValue(userNameAndUUID)
            print("first block")
        }else {
            print("second block")
            //do some other stuff
        }
    })
}

The problem I am having , is that IF the username is unique (does not exist) then BOTH print statements of the if/else are running. Output: first block second block

If the name is NOT unique, it is properly skipping the if portion of the if/else.

Why are both sections of the if/else statement running?

Thanks for any help.

The behavior you're seeing is indeed intended. Since you're attaching an observer, the first if block is being run for a unique name, but within that block, you're setting a value.

This triggers the callback again, which this time, will run through the else block.

The correct way to change this code is to use observeSingleEventOfType , so that you only read the value once and do not observe it continuously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM