使用Swift将特定键/值对保存到Firebase中的用户类

时间:2016-01-11 16:55:00

标签: swift firebase swift2

我正在尝试将用户缩略图图像作为base64字符串保存到Firebase上相应的登录用户对象,如下所示:

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)
}

但不幸的是,它一直在删除其他键。我有一种感觉,我做错了。如何在不删除所有其他键值对的情况下将其保存到现有对象(即使对象上不存在profileThumbnail键)?

2 个答案:

答案 0 :(得分:2)

Jay解决方案的替代方案是使用split

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)
}

答案 1 :(得分:1)

更新中需要另一个级别,因此您不会覆盖整个节点。有几种方法可以实现这一目标,但这是一个选项。

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)

}