Swift2从Firebase中检索图片
我正在尝试从Firebase读取/显示图片。 我首先编码图像,然后将这个编码的string发布到Firebase。 这运行良好。 当我尝试解码来自Firebase的编码string并将其转换为图像时,我得到一个零值exception。
这就是我将图像保存到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. } }
错误说:“致命错误:意外地发现零,而解包一个可选的值”; decodeData是零。 有人可以解释什么是错的。
代替
let decodedData = NSData(base64EncodedString: self.base64String as String, options: NSDataBase64DecodingOptions())
尝试添加IgnoreUnknownCharacters
NSDataBase64DecodingOptions.IgnoreUnknownCharacters
使用示例:编码一个jpg,存储并从firebase读取
编码和写我们最喜爱的明星船
if let image = NSImage(named:"Enterprise.jpeg") { let imageData = image.TIFFRepresentation let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) let imageRef = myRootRef.childByAppendingPath("image_path") imageRef.setValue(base64String)
读取和解码
imageRef.observeEventType(.Value, withBlock: { snapshot in let base64EncodedString = snapshot.value let imageData = NSData(base64EncodedString: base64EncodedString as! String, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) let decodedImage = NSImage(data:imageData!) self.myImageView.image = decodedImage }, withCancelBlock: { error in print(error.description) })
Firebase工程师在这里:
强烈build议使用新的Firebase存储 API将图片上传到Firebase。 使用起来非常简单,成本低廉,并且由Google云端存储提供大规模支持。
您可以从NSData
或NSURL
上传指向本地文件(我将显示NSData
,但原则是相同的):
// Data in memory let data: NSData = ... // Create a reference to the file you want to upload let riversRef = storageRef.child("images/rivers.jpg") // Upload the file to the path "images/rivers.jpg" let uploadTask = riversRef.putData(data, metadata: nil) { metadata, error in if (error != nil) { // Uh-oh, an error occurred! } else { // Metadata contains file metadata such as size, content-type, and download URL. let downloadURL = metadata!.downloadURL // This can be stored in the Firebase Realtime Database // It can also be used by image loading libraries like SDWebImage } }
你甚至可以暂停和恢复上传,你可以很容易地监控上传进度:
// Upload data let uploadTask = storageRef.putData(...) // Add a progress observer to an upload task uploadTask.observeStatus(.Progress) { snapshot in // Upload reported progress if let progress = snapshot.progress { let percentComplete = 100.0 * Double(progress.completedUnitCount) / Double(progress.totalUnitCount) } }