我正在尝试读取/显示Firebase中的图像。我首先对图像进行编码,然后将此编码字符串发送到Firebase。这运行正常。当我尝试对Firebase中的编码字符串进行解码并将其转换为图像时,我收到了一个空值异常。
这就是我将图像保存到Firebase的方式
var base64String: NSString!
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
self.dismissViewControllerAnimated(true, completion: nil)
imageToPost.image = image
var uploadImage = image as! UIImage
var imageData = UIImagePNGRepresentation(uploadImage)!
self.base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let ref = Firebase(url: "https://XXX.firebaseio.com")
var quoteString = ["string": self.base64String]
var usersRef = ref.childByAppendingPath("goalImages")
var users = ["image": quoteString]
usersRef.setValue(users)
displayAlert("Image Posted", message: "Your image has been successfully posted!")
}
这就是我尝试从Firebase读取图像的方式
// ViewController.swift
import UIKit
import Firebase
class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
var base64String: NSString!
@IBAction func buttonClicked(sender: AnyObject) {
sender.setTitle("\(sender.tag)", forState: UIControlState.Normal)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let ref = Firebase(url: "https://XXX.firebaseio.com/goalImages/image/string")
ref.observeEventType(.Value, withBlock: { snapshot in
self.base64String = snapshot.value as! NSString
let decodedData = NSData(base64EncodedString: self.base64String as String, options: NSDataBase64DecodingOptions())
//Next line is giving the error
var decodedImage = UIImage(data: decodedData!)
self.image.image = decodedImage
}, withCancelBlock: { error in
print(error.description)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
错误显示:“致命错误:展开可选值”“时意外找到nil; decodedData为零。有人能解释一下出了什么问题吗?
2条答案
按热度按时间lf3rwulv1#
而不是
尝试添加忽略未知字符
使用示例:编码一个jpg,存储并从firebase读取
编码和编写我们最喜欢的星际飞船
读取并解码
编辑2019年5月17日
Swift 5和Firebase 6的更新
v8wbuo2f2#
消防工程师:
我强烈推荐使用新的Firebase Storage API来上传图片到Firebase。它使用简单,成本低,并且有Google Cloud Storage的支持,可以实现巨大的规模。
您可以从
NSData
或指向本地文件的NSURL
进行上传(我将展示NSData
,但原理是相同的):您甚至可以暂停和恢复上传,并且可以轻松监控上传进度: