Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user exist with firebase 3.0 + swift

I have a app that after the user use Firebase auth it store the data on the Firebase database. Before storing the data, I want to check if the username the user give already exist in the database. So if it not exist I could give the user this unique username(like every user have a unique username). So I have a textField where the user enter his username, and then press Next. Then the app should check if the username exist or not, and tell the user if he need to change it.

So the code I used to check if the username exist:

        let databaseRef = FIRDatabase.database().reference()

        databaseRef.child("Users").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

            if snapshot.hasChild(self.usernameTextField.text!){

                print("user exist")

            }else{

                print("user doesn't exist")
            }
        })  

So every time the next button is pressed, this code is called. The problem with this is that the result always remain the same as the first search (even after the textField value change). For example, if I search Jose, and Jose exist in my database so is going to print "user exist". But when I change the textField to name that don't exist, it still show "user exist".

like image 895
Idan Aviv Avatar asked Jun 15 '16 01:06

Idan Aviv


People also ask

How do you check user is exists or not in Firebase authentication?

var ref = new Firebase('https://your-app.firebaseIO-demo.com/'); // Setup a way to get your userid (Assuming using provided firebase authentication method...) var userid = getUser(authData); // Call your function to check if they are a first time user (aka exists).

How do I see total users in Firebase?

var ref = new Firebase('<my-firebase-app>/userIds'); ref. once('value', function(snap) { console. log(snap. numChildren()); });

Where are Firebase users stored?

Firebase users have a fixed set of basic properties—a unique ID, a primary email address, a name and a photo URL—stored in the project's user database, that can be updated by the user (iOS, Android, web).


1 Answers

I figured out I need to change the .Value to FIRDataEventType.Value

 if (usernameTextField.text?.isEmpty == false){
        let databaseRef = FIRDatabase.database().reference()

         databaseRef.child("Users").observeSingleEventOfType(FIRDataEventType.Value, withBlock: { (snapshot) in

            if snapshot.hasChild(self.usernameTextField.text!){

                print("true rooms exist")

            }else{

                print("false room doesn't exist")
            }


        })
like image 200
Idan Aviv Avatar answered Sep 19 '22 20:09

Idan Aviv