1
votes

In my Swift app, when signing up a user, the user is prompted to select a username. This username will then be stored in the Firebase realtime database like this: self.ref.child("users").child(user!.uid).setValue(["username": usernameResponse]), where username response is the value entered by the user. This happens as part of the sign up method:

FIRAuth.auth()?.createUserWithEmail(email, password: passwordUltimate) { (user, error) in

// ... if error != nil {

I would like to verify if the username is available before setting its value. Is there some kind of query I could use to check that there are no duplicates?

Here is my database with some sample data (qwerty12345 is the uid):

database

1
That is from the old Firebase. Could you help to convert it?GJZ
See stackoverflow.com/questions/25294478/…. While the code in the answer is for the 2.x version of Firebase and for web, the same approach applies here.Frank van Puffelen

1 Answers

2
votes
@IBAction func enterUsername(){

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

    namesRef.observeSingleEventType(.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
        }
    })
}

Alternately:

let checkWaitingRef = Firebase(url:"https://test.firebaseio.com/users")
checkWaitingRef.queryOrderedByChild("username").queryEqualToValue("\(username!)")
            .observeEventType(.Value, withBlock: { snapshot in

        if ( snapshot.value is NSNull ) {
            print("not found)")

        } else {
            print(snapshot.value)
        }
 }