image - Swift2從Firebase檢索圖像




(2)

我正在嘗試從Firebase讀取/顯示圖像。 我首先對圖像進行編碼,然後將此編碼後的字符串發佈到Firebase。 運行良好。 當我嘗試從Firebase解碼編碼的字符串並將其轉換為圖像時,出現了nil值異常。

這就是我將圖像保存到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”; encodedData為零。 有人可以解釋出什麼問題了。


Firebase工程師在這裡:

我強烈建議使用新的 Firebase Storage API將圖像上傳到Firebase。 它使用簡單,成本低廉,並得到了 Google Cloud Storage 的大規模支持。

您可以從 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)
  }
}

代替

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

編輯2019_05_17

更新到Swift 5和Firebase 6

func writeImage() {
    if let image = NSImage(named:"Enterprise.jpg") {
        let imageData = image.tiffRepresentation
        if let base64String = imageData?.base64EncodedString() {
            let imageRef = self.ref.child("image_path")
            imageRef.setValue(base64String)
        }
    }
}

func readImage() {
    let imageRef = self.ref.child("image_path")
    imageRef.observeSingleEvent(of: .value, with: { snapshot in
        let base64EncodedString = snapshot.value as! String
        let imageData = Data(base64Encoded: base64EncodedString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
        let decodedImage = NSImage(data: imageData)
        self.myImageView.image = decodedImage
    })
}




swift2