Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do update a value inside my Firebase Database from a different class?

I have a Registration Class that has 3 textfields for a username, email and password. When the user hits the Sign Up button, a handleRegister() function is called. This function takes the three values from these textfields.text and sends them to my Firebase database under a child node, containing their user id like in the image below:

enter image description here

My problem is that I want to be able to UPDATE any 3 of these values (email, name, password) OUTSIDE of the registration class. How do I do achieve this? Thank you. Here registration my code:

func handleRegister() {

    guard let email = emailTextField.text, let password = passwordTextField.text, let name = usernameTextField.text else {
        return
    }

    FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in

        if error != nil {
            return
        }

        guard let uid = user?.uid else {
            return
        }

        //successfully registered user.

        let imageName = NSUUID().uuidString

        let storageRef = FIRStorage.storage().reference().child("profile_images").child("\(imageName).png")

        if let uploadData = UIImagePNGRepresentation(self.profileImageView.image!) {
            storageRef.put(uploadData, metadata: nil, completion: { (metadata, error) in

                if error != nil {
                    return
                }

                if let profileImageUrl = metadata?.downloadURL()?.absoluteString {
                    let values = ["name": name, "email": email, "password": password, "profileImageUrl": profileImageUrl]

                    self.registerUserIntoDatabaseWithUID(uid: uid, values: values as [String : AnyObject])
                }
            })
        }
    })
}

private func registerUserIntoDatabaseWithUID(uid: String, values: [String: AnyObject]) {

    let ref = FIRDatabase.database().reference()

    let usersReference = ref.child("users").child(uid)

    usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in

        if err != nil {
            return
        }
        print("Successfully saved user to database.")

        self.dismiss(animated: true, completion: nil)
    })
}
like image 386
Daniel Dramond Avatar asked Dec 08 '25 14:12

Daniel Dramond


2 Answers

You have two options:

Option 1: You need to save your user's database ID somewhere so you can use it later on in the app for situations just like this. You can save the ID in your Userdefaults or somewhere else that's a bit more secure.

Option 2: You can retrieve the ID of the logged in user by using Auth.auth()?.currentUser?.uid

guard let uid = Auth.auth()?.currentUser?.uid else { return }

When you have this ID you can update the value in the database like you are doing in registerUserIntoDatabaseWithUID().

func updateEmailAddress(text: String) {
   guard let uid = Auth.auth()?.currentUser?.uid else { return }

   let userReference = Database.database().reference.child("users/(uid)")

   let values = ["email": text]

   // Update the "email" value in the database for the logged in user
   userReference.updateChildValues(values, withCompletionBlock: { (error, ref) in
        if error != nil {
            print(error.localizedDescription)
            return
        }

        print("Successfully saved user to database.")
        self.dismiss(animated: true, completion: nil)
   })
}
like image 198
Jordi Bruin Avatar answered Dec 11 '25 07:12

Jordi Bruin


Nota Bene

If you have any questions regarding this answer please add a comment. The difference between this and the other answer is that I am indicating how you can update in multiple locations as requested.

You'd want to look at using the data fan out approach. It deals with writing the data at mulitple locations. Here is a quick code sample:

let key = ref.child("posts").childByAutoId().key
let post = ["uid": userID,
            "author": username,
            "title": title,
            "body": body]
let childUpdates = ["/posts/\(key)": post,
                    "/user-posts/\(userID)/\(key)/": post]
ref.updateChildValues(childUpdates)

To read more about this approach see the documentation at: https://firebase.google.com/docs/database/ios/read-and-write#update_specific_fields

like image 23
Tommie C. Avatar answered Dec 11 '25 09:12

Tommie C.