Check if user exists with username using Swift and Firebase

随声附和 提交于 2019-12-24 22:39:07

问题


I'm currently trying to code a function who pass the user Data when user exists. When the username is in the database, the code is okay, but if there is no username recorded in the database I don't know how to have a return function.

I'm beginner, this is what I did:

func observeUserByUsername(username: String, completion: @escaping (Userm?) -> Void) {
      REF_USERS.queryOrdered(byChild: "username_lowercase").queryEqual(toValue: username).observeSingleEvent(of: .childAdded) { (snapshot) in

         if let dict = snapshot.value as? [String: Any] {
            let user = Userm.transformUser(dict: dict, key: snapshot.key)
            completion(user)
         } else {
            print("no user")
            completion(nil)
         }
      }
}

I would like to have something like this: if there is user with this username -> return nil (for the completion).

Do you know how I could do this?


回答1:


So if I got it right, you want to just check if a user with the username exists. You can just enter the path to firebase and use the exists() method to check if this subnode exists. I have a similar method, you can maybe change it to fit into your project.

func checkUsernameAvailability(completion: @escaping (_ available:Bool)->()){
    guard let lowercasedText = usernameTextField.text?.lowercased() else {completion(false); return}
    let ref = Database.database().reference().child("users").child("username").child(lowercasedText)
    ref.observeSingleEvent(of: .value) { (snapshot) in
        if snapshot.exists(){
            completion(false)
            return
        }else{
            completion(true)
        }
    }
}

Be careful, Firebase is not case-sensitive (that's why I always check and also store the lowercased version). If your subnode e.g. is 'UserName' and you search for the name 'username' it will tell you that there is already one with this name.



来源:https://stackoverflow.com/questions/47907667/check-if-user-exists-with-username-using-swift-and-firebase

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