首页 > 解决方案 > Kingfisher nil 同时展开可选值

问题描述

我有一个Medicine结构,其中包含image_origin要下载并设置为 ImageView 的图像的 URL。出于下载/缓存目的,我正在使用Kingfisher框架。

    let m = medicines[indexPath.row]

    cell.medicineImage.kf.setImage(with: URL(string: m.value(forKeyPath: "image_origin") as! String)!)
    cell.medicineName.text = m.value(forKeyPath: "i_name") as? String

在上面的代码m中是一个NSManagedObjectof CoreData。我尝试从 CoreData 获取图像 URI 并将其设置为 ImageView,但每次在第 2 行我都会收到以下错误消息:Unexpectedly found nil while unwrapping an Optional value

我尝试更改变量和可选类型,尝试对 URI 进行硬编码但没有成功。

我究竟做错了什么?

PS我正在使用Swift4

标签: iosswiftxcodecore-datakingfisher

解决方案


只需安全地打开包装以修复崩溃并检查您的数据库,如果您没有urlString正确获取,

if let urlString = m.value(forKeyPath: "image_origin") as? String {
   print(urlString)
   guard let url = URL(string: urlString) else { return }
   cell.medicineImage.kf.setImage(with: url)
}

推荐阅读