allenhinson214
allenhinson214

Reputation: 165

Storing data in Firebase Real Time Database

So I am trying to store some data to my real time database. I currently have two separate view controllers, one is for the user to sign up and the other is for the user to select their profile image and be able to change that image. On the sign up page, I have the "username" saved to firebase like this:

 let ref = Database.database().reference().root

                    let userObject = [
                        "username":fullname
                    ] as [String:Any]
                    ref.child("users/profile").child((result!.user.uid)).setValue(userObject)

And for the profile image I have the data saved like this

  func saveProfileImage(profileURL:URL, completion: @escaping ((_ url: URL?) -> ())){
        guard let uid = Auth.auth().currentUser?.uid else { return }
        let databaseRef = Database.database().reference().child("users/profile/\(uid)")
        let userObject = [
            "photoURL": profileURL.absoluteString
        ] as [String:Any]
        self.ref.child("users/profile").child(uid).setValue(userObject)
        }

I want both data to be saved under Users -> Profile -> UID and have the observed values of "username" and "photoURL" under the UID. Only problem I am having now is that when I signup for an account it saves the username correctly under the UID node, and once I save the profile Image for the user it saves under the UID node but replaces the "username" node. I am wondering, how do I save both of those pieces of data under Users -> Profile -> UID with the username and photoURL being on separate view controllers.

Upvotes: 0

Views: 58

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598837

When you call setValue() on a location, you're replacing all data at that location with the value(s) you specify. To instead update existing data, use updateChildValues.

So something like:

self.ref.child("users/profile").child(uid). updateChildValues(userObject)

For more on this, see the Firebase documentation on updating or deleting data.

Upvotes: 1

Related Questions