Timmy Sorensen Timmy Sorensen - 6 months ago 1947
Swift Question

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

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

Answer

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