Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase querying for unique Username swift

I searched for this question, but none of them had an answer that worked for me.

I want to make it so when a user registers an account, it checks to see if the username they have entered already exists, before creating the account. I have tried using querying in firebase, but I just can't seem to get it to work.

Here is an image of what my firebase data looks like: My firebase data tree

How would I use query to find the string for the key "username"?

like image 825
Big Johnson Avatar asked May 15 '17 04:05

Big Johnson


2 Answers

You can go like this, make one function with completion block to check username is already exist in your Firebase DB and create new user on the basis of it

func checkUserNameAlreadyExist(newUserName: String, completion: @escaping(Bool) -> Void) {

    let ref = FIRDatabase.database().reference()
    ref.child("users").queryOrdered(byChild: "username").queryEqual(toValue: newUserName)
              .observeSingleEvent(of: .value, with: {(snapshot: FIRDataSnapshot) in

        if snapshot.exists() {
            completion(true)
        }
        else {
            completion(false)
        }
    })
}

Now simply call this function when you create new user:

self.checkUserNameAlreadyExist(newUserName: "Johnson") { isExist in
    if isExist {
        print("Username exist")
    }
    else {
        print("create new user")
    }
}
like image 179
Nirav D Avatar answered Nov 02 '22 14:11

Nirav D


This is how I do it:

var text = "Your username"

let dbRef = FIRDatabase.database().reference().child("users")
dbRef.queryOrdered(byChild: "name").queryEqual(toValue: text).observeSingleEvent(of: .value, with: { snapshot in
    if !snapshot.exists() {
         // Name doesn't exist
    }

    if let data = snapshot.value as? [String: [String: String]] {
         // it should exist if it reaches here
    }
})

Make sure in your database rules to index the "users" node on "name" for performance optimization.

like image 3
MarksCode Avatar answered Nov 02 '22 14:11

MarksCode