How to check unique username in Firebase Database (swift)

坚强是说给别人听的谎言 提交于 2019-12-24 20:30:27

问题


I've Firebase Database where each user has own email and username. How to check unique username? I tried to make it like this, but my code doesn't work properly therefore different users can have the same username

  usernameField.isHidden = false
    let username:String = self.usernameField.text!

    if (usernameField.text?.isEmpty == false){
    ref.child("users").queryOrdered(byChild("username").queryEqual(toValue: username).observeSingleEvent(of: .value, with: { snapshot in

            if snapshot.exists(){

                print("username exist")

            }else{

                ref.root.child("users").child(userID).updateChildValues(["username": username])
            }

        })
}

I'm a little bit newbie in Firebase I store email and username for each user like this newUserReference.setValue(["username":String(), "email" : self.emailTextField.text!]). On next view, user can type username in usernameField.text and this value will be added in Firebase Database. But if the next user (user 2) will type the same username like previous user, it must be blocked, because username should be unique


回答1:


You still need to indicate what property you want to order/filter on with queryOrdered(byChild:):

if (usernameField.text?.isEmpty == false){
    ref.child("users").queryOrdered(byChild:"username").queryEqual(toValue: username).observeSingleEvent(of: .value, with: { snapshot in

        if snapshot.exists(){



回答2:


If you're trying to store your user's id on login do this when you receive a successful response to the login:

create a Shared Instance to store the ID

class userDataSource {
    var id : String? // variable to store your users ID
    static let sharedInstance = PageDataSource() // global access to this dataSource
    private init() {}
}

Assign the id a value after successful login

func getIDFromLogin() {
    if let user = Auth.auth().currentUser {
        print(user.uid)
        userDataSource.sharedInstance.id = user.uid
    }
}

Then you can do this to view each id:

 ref.child("users").observeSingleEvent(of: .value, with: { snapshot in
     if let snapshots = snapshot.children.allObjects as? [DataSnapshot] { 
         for snap in snapshots {
             print(snap.key) // you can compare userDataSource.sharedInstance.id to this value
         } 
     }     
 })

Or if you just want that user's data do this:

ref.child("users").child(userDataSource.sharedInstance.id!).observeSingleEvent(of: .value, with: { snapshot in
     if let snapshots = snapshot.children.allObjects as? [DataSnapshot] { 
             for snap in snapshots {
                 print(snap) 
         } 
     }     
 })

Edit to answer your question more accurately

Here is an answer more inline with your question. First thing I will recommend is for you to add a table to Firebase that only contains the usernames, and the .uid's that they belong to. You will need to first read through that table to make sure that no one else has that username, then update the table accordingly:

// This function will check through all of the usernames and return a true or false value in the completion handler
func checkUsernames(_ completion: @escaping(_ success: Bool) -> Void) {
    ref.child("usernames").observeSingleEvent(of: .value, with: { snapshot in
        if let snapshots = snapshot.children.allObjects as? [DataSnapshot] { 
            for snap in snapshots {
                if snap.value == username {
                    completion(false)
                }
            }
            completion(true) 
        } else {
            completion(true) // TODO: check for errors before setting completion
        }     
    })
}

// this function will set the username values in Firebase
func storeUsername() {
    let usernameRef = ref.child("usernames")
    usernameRef.updateChildValues(["\(userDataSource.sharedInstance.id!)" : username])
        }
    }
}

Assuming you have already handled your username variable and set it's value, you will call the functions like this:

checkUsernames({ (success) in
    if success {
        storeUsername()
        // you may also want to update your "users" table here as well
    } else { print("Duplicate Username") } // handle alert or something here
})


来源:https://stackoverflow.com/questions/49408465/how-to-check-unique-username-in-firebase-database-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!