简体   繁体   English

Swift2从Firebase检索图像

[英]Swift2 retrieving images from Firebase

I am trying to read/display an image from Firebase. 我正在尝试从Firebase中读取/显示图像。 I am first encoding the image and then posting this encoded String to Firebase. 我首先编码图像,然后将此编码的字符串发布到Firebase。 This runs fine. 这很好。 When I try and decode the encoded string from Firebase and convert it to an image, I am getting a nil value exception. 当我尝试从Firebase解码编码的字符串并将其转换为图像时,我得到一个零值异常。

This is how I am saving the image to 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!")
}

This is how I am trying to read the image from Firebase 这就是我尝试从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.
}
}

The error says: "fatal error: unexpectedly found nil while unwrapping an Optional value"; 错误说:“致命错误:在展开Optional值时意外发现nil”; decodedData is nil. decodingData是零。 Could someone explain what is going wrong. 有人可以解释出了什么问题。

Instead of 代替

let decodedData = NSData(base64EncodedString: self.base64String as String, 
                                     options: NSDataBase64DecodingOptions())

try adding IgnoreUnknownCharacters 尝试添加IgnoreUnknownCharacters

NSDataBase64DecodingOptions.IgnoreUnknownCharacters

Use Example: Encode a jpg, store and read from firebase 使用示例:编码jpg,存储和读取firebase

encode and write our favorite starship 编码并写下我们最喜欢的星舰

    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)

read and decode 读取和解码

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

EDIT 2019_05_17 编辑2019_05_17

Update to Swift 5 and Firebase 6 更新到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
    })
}

Firebase Engineer here: Firebase工程师在这里:

I highly recommend using the new Firebase Storage API for uploading images to Firebase. 我强烈建议您使用新的Firebase存储 API将图像上传到Firebase。 It's simple to use, low cost, and backed by Google Cloud Storage for huge scale. 它使用简单,成本低,并且大规模支持Google云端存储

You can upload from NSData or an NSURL pointing to a local file (I'll show NSData , but the principle is the same): 您可以从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
  }
}

You can even pause and resume uploads, and you can easily monitor uploads for progress: 您甚至可以暂停和恢复上传,并可以轻松监控上传进度:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM