解码Firebase base64 Swift 2.0

时间:2016-02-16 20:38:34

标签: swift firebase decode

我正在尝试加载存储在Firebase服务器中的图像。我正在检查其他答案,但我无法找到为什么我能够打印正确的字符串值后得到一个零:

在我的应用程序中,我有以下数据结构:

Structure

这里是我用来加载它的代码( nil 值是评论中显示的值)

let profileDetailsRef = self.ref.childByAppendingPath("users/" + sessionUserID + "/details")

    profileDetailsRef.observeEventType(.Value, withBlock: { snapshot in 
        self.txtUsername.text = sessionUserID
        self.txtDisplayName.text = snapshot.value.objectForKey("nameToDisplay") as? String

        let base64EncodedString = snapshot.value.objectForKey("userImage")! as! String

        print(base64EncodedString) //Here it's printing well because I get the same value as shows in the dasboard so it finds it

        //But the value "decodedData" here below is returning **nil**
        let decodedData = NSData(base64EncodedString: base64EncodedString as! String, options: NSDataBase64DecodingOptions())

        let decodedImage = UIImage(data: decodedData!)!

        self.imageUserImage.image = decodedImage

        }, withCancelBlock: { error in
            print(error.description)
    })

谢谢!

1 个答案:

答案 0 :(得分:3)

使用像Cloudinary这样的图片托管API可能要容易得多,只需将该网址存储在Firebase中。

尽管如此,问题很可能是您的编码和解码选项不匹配。尝试在每个选项字段中提供[]。例如,要编码:

let image = [#Image(imageLiteral: "icon.png")#] // your UIImage
let imageData = UIImagePNGRepresentation(image)! // or however you store your image
let base64EncodedString = imageData.base64EncodedStringWithOptions([])

要解码:

if let decodedData = NSData(base64EncodedString: base64EncodedString, options: []),
   let decodedImage = UIImage(data: decodedData) {
    // do something with decodedImage
}

如果这不起作用,Firebase可能会截断您的图片,因为字符串长度超出了限制。

这种方法不是存储和加载图像的好方法 - 您错过了HTTP缓存,内容类型,服务器端优化等等 - 所以如果可以,我会尽量避免。< / p>