Firebase存储图像下载无法正常运行

时间:2017-09-27 22:02:57

标签: ios swift firebase-storage

我使用以下代码从Firebase存储中下载图像:

storageRef.child(self.fileImageDownloadPath).getData(maxSize: 1 * 1024 * 1024) { (data, error) -> Void in

    let userPhoto = UIImage(data: data!)

    // ASSIGNS DOWNLOADED PICTURE TO OUTLET
    self.sharedProfileImage.image = userPhoto

    print("– – – Succesfully downloaded the shared profile picture")

}

从相应的Firebase数据库成功检索下载路径;然而,由于表达式let userPhoto = UIImage(data: data!),应用程序总是崩溃;控制台记录

  

致命错误:在解包可选值时意外发现nil

如果我尝试简单地使用let userPhoto = UIImage(data: data),则会发生编译错误:

  

可选类型'数据'的值?没有打开;你的意思是用'!'还是'?'?

你知道我怎么解决这个问题吗?一般来说,我很清楚如何(安全地)打开选项 - 但我自己也无法解决这个问题。

2 个答案:

答案 0 :(得分:0)

以下解决了这个问题:

storageRef.child(self.fileImageDownloadPath).getData(maxSize: 10 * 1024 * 1024) { (data, error) -> Void in

    if (error != nil) {

        print(error!.localizedDescription)

    } else {

        self.sharedProfileImage.image = UIImage(data: data!)
        print("– – – Succesfully downloaded the shared profile picture")

    }

}

有了这个,我发现了

  

对象https:/ firebasestorage.googleapis.com/v0/b / [...]不存在

这显然是因为

中缺少斜杠
  

的https:/火力[...]

答案 1 :(得分:0)

这样您可以将文件下载为NSData

// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
islandRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
  if let error = error {
    // Uh-oh, an error occurred!
  } else {
    // Data for "images/island.jpg" is returned
    let image = UIImage(data: data!)
  }
}

下载到本地文件

// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")

// Create local filesystem URL
let localURL = URL(string: "path/to/image")!

// Download to the local filesystem
let downloadTask = islandRef.write(toFile: localURL) { url, error in
  if let error = error {
    // Uh-oh, an error occurred!
  } else {
    // Local file URL for "images/island.jpg" is returned
  }
}