且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查用户是否存在Firebase 3.0 + Swift

更新时间:2023-11-25 21:30:34

我想我需要将 .Value 更改为 FIRDataEventType.Value

  if(usernameTextField.text?.isEmpty == false){
let databaseRef = FIRDatabase.database()。如果使用snapshot.hasChild(self.usernameTextField),则参考()

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

。 ){

print(true room exists)

} else {

print(false room does not exist)
}


})


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".

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")
            }


        })