Firebase存储图像下载

时间:2016-11-30 00:33:35

标签: ios swift firebase firebase-storage

我正在尝试从Firebase存储中下载图片。

func downloadThumbnail(thumbnail: String) -> URL {
    var thumb: URL!
    let _ = DataService.dataService.TAG_PHOTO_REF.child("\(thumbnail)").downloadURL { (thumbnailUrl, error) in
        if error != nil {
            print(error?.localizedDescription as Any)
        } else {
            thumb = thumbnailUrl
        }
    }
    return thumb
}

cell.photo.kf.setImage(with: downloadThumbnail(thumbnail: selectedTag.thumbnail))

当我运行此代码时,我得到了

  

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

return thumb行。

但如果我只运行print(thumbnailUrl)而不是返回,则会打印正确的缩略图网址。谁知道为什么我会收到这个错误?

感谢。

1 个答案:

答案 0 :(得分:2)

你不能保证拇指永远不会是零。因此,你不应该使用!由于您无法控制它并且未手动设置,因此您需要将其设为可选项。

var thumb: URL?

其次,您有互联网电话。在你收到来自该电话的回复之前你正在回头拇指,因此,拇指是零,但你告诉我们了!这是不可能的,所以你崩溃了。

如果您输入了断点,您应该注意到在点击return thumb行之前,您将在方法上点击if error != nil。您不能为此使用返回,因为该方法将始终在从firebase获得响应之前返回,因此您的URL将始终为nil。我会在完成时发送一个URL。

我还没有检查过firebase代码,但是如果一切正确的话,这就是你想要的顺序。

所以:

func downloadThumbnail(thumbnail: String,withCompletion comp: @escaping (URL?, Error?) -> ()) {
  let _ = DataService.dataService.TAG_PHOTO_REF.child("\(thumbnail)").downloadURL { (thumbnailUrl, error) in
    if error != nil {
        print(error?.localizedDescription as Any)
        comp(nil, error)
    } else {
        comp(thumbnailUrl, nil)
    }
  }
}

所以当你在其他地方打电话时:

func getMyImage(cell: UITableViewCell) {
  downloadThumbnail(thumbnail: selectedTag.thumbnail) { (thumbnailUrl, error) in 
    if error != nil {
      //show some sort of alert for the user here? or do something to handle the error?
    } else {
      //the url is an optional URL, so check to make sure it isn't nil
      if let url = thumbnailUrl {
        cell.photo.kf.setImage(with: url)
      } else {
        //you didn't get an error from your firebase response
        //but the thumbnail url it gave you is broken for some reason
        //so again, do something about your error here
    }
  }
}

如果这与您的应用的设计模式不符,请与我们联系。我假设您使用的是tableview,并且这些方法可能位于不同的类中。

相关问题