Jamie22
Jamie22

Reputation: 424

Saving specific key/value pair to user class in Firebase using Swift

I'm attempting to save a user thumbnail image as a base64 string to the appropriate logged in user object on Firebase like so:

if self.myRootRef.authData != nil {
    let profileId = self.myRootRef.authData.uid
    let myThumbnail = self.profileImage.image!.resizeToWidth(75.0)
    let imageData:NSData = UIImageJPEGRepresentation(myThumbnail, 0.7)!
    self.base64String = imageData.base64EncodedStringWithOptions([])
    let fString = ["profileThumbnail": self.base64String]

    self.userRef.childByAppendingPath(profileId).setValue(fString)
}

But unfortunately, it keeps removing the other keys. I have a feeling I'm doing this wrong. How would I save this to an already existing object (even if the profileThumbnail key doesn't exist on the object) without removing all other key value pairs?

Upvotes: 0

Views: 915

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598765

An alternative to Jay's solution is to use updateChildValues:

if self.myRootRef.authData != nil {
    let profileId = self.myRootRef.authData.uid
    let myThumbnail = self.profileImage.image!.resizeToWidth(75.0)
    let imageData:NSData = UIImageJPEGRepresentation(myThumbnail, 0.7)!
    self.base64String = imageData.base64EncodedStringWithOptions([])
    let fString = ["profileThumbnail": self.base64String]

    self.userRef.childByAppendingPath(profileId).updateChildValues(fString)
}

Upvotes: 2

Jay
Jay

Reputation: 35648

You need another level in the update so you are not overwriting the entire node. There are several ways to accomplish this but here's an option.

if self.myRootRef.authData != nil {

      let profileId = self.myRootRef.authData.uid
      let myThumbnail = self.profileImage.image!.resizeToWidth(75.0)
      let imageData:NSData = UIImageJPEGRepresentation(myThumbnail, 0.7)!
      self.base64String = imageData.base64EncodedStringWithOptions([])
      //you may NSDataBase64DecodingOptions.IgnoreUnknownCharacters in options
      let fString = blah blah

      let thisUserRef = self.userRef.childByAppendingPath(profileId)
      let thisUserProfileRef = thisUserRef.childByAppendingPath("profileThumbnail")
      thisUserProfileRef.setValue(fString)

}

Upvotes: 1

Related Questions