1

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

Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
GJZ
  • 2,482
  • 3
  • 21
  • 37
  • That is from the old Firebase. Could you help to convert it? – GJZ Jun 05 '16 at 17:55
  • See http://stackoverflow.com/questions/25294478/how-do-you-prevent-duplicate-user-properties-in-firebase. 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 Jun 05 '16 at 18:58

1 Answers1

3
@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)
        }
 }
Hack-R
  • 22,422
  • 14
  • 75
  • 131
  • 1
    Having the `users` world readable is a bad practice since you might have sensitive data over there. It would be better to enforce your policy using the database rules – Itai Hanski Jun 07 '16 at 10:55