首页 > 解决方案 > 从存储下载图像时出现可选错误,我已将字符串转换为 URL

问题描述

从 Firebase 存储下载图像时出现可选错误,我正在将字符串转换为 URL 以下载图像

这是发生错误的代码,如果需要更多代码,请告诉我

let imageUrl = URL(string: post._postuserprofileImagUrl)
        ImageService.getImage(withURL: imageUrl) { image in
            self.profileImageView.image = image
        }

标签: iosswiftfirebasegoogle-cloud-firestorestorage

解决方案


您必须(安全地)打开 URL 实例

if let imageUrl = URL(string: post._postuserprofileImagUrl) {
        ImageService.getImage(withURL: imageUrl) { image in
            self.profileImageView.image = image
        }
}

甚至(如果postuserprofileImagUrl也是可选的)

if let userprofileImagUrl =  post._postuserprofileImagUrl,
   let imageUrl = URL(string: userprofileImagUrl) {
        ImageService.getImage(withURL: imageUrl) { image in
            self.profileImageView.image = image
        }
}

推荐阅读