2

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
KevinB
  • 2,454
  • 3
  • 25
  • 49

1 Answers1

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.

cloo_coder
  • 37
  • 7