How to download and view images from the new Firebase Storage?

空扰寡人 提交于 2020-01-11 09:48:08

问题


I am able to upload images to Firebase Storage but I am having trouble downloading them. This is my code to download images:

let storage = FIRStorage.storage()
let localURL : NSURL! = NSURL(string: "file:///Documents/co.png")
// i also tried let localURL : NSURL! = NSURL.fileURLWithPath("file:///Documents/co.png")

func download() {
    let storageRef = storage.referenceForURL("gs://project-5547819591027666607.appspot.com")
    let imageRef = storageRef.child("co.png")

    let downloadTask = imageRef.writeToFile(localURL) { (URL, error) -> Void in
        if (error != nil) {
            print(error?.localizedDescription)
        }
        else {
            self.imageView.image = UIImage(data: data!)
        }
    }
}

I am receiving - Optional("An unknown error occurred, please check the server response.")

Also once I get them downloaded How would I view that image?

For trying to see if the image was downloaded I created a UIImageView and set an outlet for it in storyboard called "imageView" then set the downloaded image to the UIImageView.

self.imageView.image = UIImage(data: data!)

回答1:


Try

first getting reference to the image you want to download using

let reference = FIRStorage.storage().reference("uploads/sample.jpg")

If you know the size of image is low - like 1-2 mb max . download the image in memory

reference.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
     let myImage: UIImage! = UIImage(data: data!)    
  }
}

This will be the quickest and easy way to download directly from Firebase Storage.

However there are cases when you want the progress blocks and certain other things like caching. In such cases you could use any third party like Alamofire to download the image from the url you get from Firebase Storage.
To get the url do something like this

reference.downloadURLWithCompletion { (URL, error) -> Void in
  if (error != nil) {
    // Handle any errors
  } else {
     print(URL)
     // download image using NSURLSession or Alamofire
  }
}


来源:https://stackoverflow.com/questions/37694009/how-to-download-and-view-images-from-the-new-firebase-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!