Search code examples
iosswiftxcodecore-datakingfisher

Kingfisher nil while unwrapping optional value


I have Medicine struct that holds image_origin URL of image I want to download and set to the ImageView. For downloading/caching purposes I'm using Kingfisher framework.

    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

In the code above m is an NSManagedObject of CoreData. I try to get image URI from the CoreData and set it to the ImageView, but every time at the line 2 I get the following error message: Unexpectedly found nil while unwrapping an Optional value

I have tried changing variables and Optinal types, tried to hardcode URI but without success.

What am I doing wrong?

P.S. Im using Swift4


Solution

  • Just unwrap safely to fix the crash and check your database if you are not getting the urlString properly,

    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)
    }