crispy2k12 crispy2k12 - 1 year ago 237
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 Source

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


enter image description here

sample code:

    @IBAction func ActionRegister(sender: UIButton) {

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

          // following method is a add user's  more details
          ref.child("users").child(user!.uid).setValue(["Provider": "1234566", "Email": "", "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)")

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download