crispy2k12 crispy2k12 - 5 months ago 99
iOS Question

Firebase: linking user UID to database

I'm trying to use the current users uid as a unique identifier to store the associated user data as there user uid in the realtime database i.e. ref.child("User/uid"):

Example: When a user creates an account its added to the authentication section of the Firebase console and lets say the user fills in a form i.e first name, last name, DOB etc. how would i link the data to a user UID in the realtime database.

Answer

When you register any new user you need to do first register code:

 FIRAuth.auth()?.createUserWithEmail(UserEmail, password: UserPassword, completion: { (user, error) in

On the success response you can set the user more details use dictionary and use SetValue method by adding Child using following code:

ref.child("users").child(user!.uid).setValue(["Provider": self.txtPassword.text!,"Email": self.txtEmail.text!,"Firstname": self.txtFName.text!,"Lastname": self.txtLname.text!,"Phone": self.txtPhone.text!,])

Here user!.uid is a unique user id child in your main USER tree.

so your firebase tree look like :

enter image description here

and

enter image description here

sample code:

    @IBAction func ActionRegister(sender: UIButton) {

                let ref : FIRDatabaseReference!
                ref = FIRDatabase.database().reference()
                FIRAuth.auth()?.createUserWithEmail("abc@abc.com", password: "1234567", completion: { (user, error) in
                    if((error) != nil)
                    {
                        print("Error is = \(error?.localizedDescription)")
                    }
                    else
                    {

          // following method is a add user's  more details
          ref.child("users").child(user!.uid).setValue(["Provider": "1234566", "Email": "abc@abc.com", "Firstname": "nitin", "Lastname": "Gohel", "Phone": "12345678" ])

         //following method get the registers user details 
         ref.child("users").child(user!.uid).observeSingleEventOfType(.Value, withBlock: { snapshot in
                            let postDict = snapshot.value as! [String : AnyObject]
                            print("Error is = \(postDict)")
                        })    
                    }
                })

            }
Comments