从 Fire Storage 检索图像,但是如果图像不存在,应用程序会崩溃

Retrieving image from Fire Storage however if the image does not exist the app crashes

您好,我最近想出了如何使用 UIImagePickerController 将图像上传和图像到 Firebase 存储,以及如何在我的视图控制器上的 UIImageView 中显示该图像,但是问题是如果该文件在 Fire 中尚不存在存储然后应用程序崩溃,我什至没有机会上传图像。我对此很陌生,所以我希望有人可以简单地修复我的代码,了解我如何检索图像。我想从 Fire 中检索图像。存储,但如果该图像尚不存在,则它不会使应用程序崩溃,而只是过度查看它。这是我用来检索有效图像的代码,但前提是图像已经存在。感谢您的帮助!

我得到的错误是在解包可选值时意外地发现 Nil

//使用 Firestore 数据库从 Firestorage 检索上传的照片 - 当前用户 - 已登录并将图像显示到 ViewController 中的 UIImageView 调用 profileimage.image

func downloadimages() {
    let reference = Storage.storage().reference(withPath: "\("images/"+Auth.auth().currentUser!.uid+"+.jpg")")
    reference.downloadURL { (url, error) in
        let data = NSData(contentsOf: url!)
        let image = UIImage(data: data! as Data)
        self.profileimage.image = image
    }
}

我也找到了这个问题的解决方案,并希望 post 以防任何新编码员遇到同样的问题。我只需要添加

if error != nil {
  print(error!.localizedDescription)
  return
}

完整示例

func downloadimages() {
    let reference = Storage.storage().reference(withPath: "\("images/"+Auth.auth().currentUser!.uid+"+.jpg")")
    reference.downloadURL{(url, error) in
        if error != nil {
            print(error!.localizedDescription)
            return
        }
        let data = NSData(contentsOf: url!)
        let image = UIImage(data: data! as Data)
        self.profileimage.image = image
    }
}