如何从新的Firebase存储下载和查看图像? [英] How to download and view images from the new Firebase Storage?

查看:83
本文介绍了如何从新的Firebase存储下载和查看图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够将图像上传到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.")

我也下载了它们,又该如何查看该图像?

为尝试查看图像是否已下载,我创建了一个UIImageView并在情节提要中为其设置了一个插座"imageView",然后将下载的图像设置为UIImageView.

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

推荐答案

尝试

首先获取要使用

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

如果您知道图像的大小很低,例如1-2 mb max.将图像下载到内存中

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

这是直接从Firebase Storage直接下载的最快,最简单的方法.

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

但是,在某些情况下,您需要进度块和某些其他内容(例如缓存).在这种情况下,您可以使用Alamofire之类的任何第三方从您从Firebase Storage获得的URL中下载图像.
要获取网址,请执行以下操作

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

这篇关于如何从新的Firebase存储下载和查看图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆