Saving uiimage to core data from a if statement

In my swift code below the goal is to save the uiimage into core data from the view did load function. I have added a pic of the error below. Don’t know what I am missing in the code below. My code is using 2 different classes.

  override func viewDidLoad() {
        super.viewDidLoad()
        
        //
        let gwen = UIImage(named: "f.jpeg")
        if let imageData = gwen.self?.pngData() {
            DataBaseHelper.shareInstance.saveImage(data: imageData)
        }

        let arr = DataBaseHelper.shareInstance.fetchImage()
        let jake = Int()
        print("core data number is : ", arr[jake].img!.count)

}


class DataBaseHelper {

static let shareInstance = DataBaseHelper()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

func saveImage(data: Data) {
    let imageInstance = Info(context: context)
    imageInstance.img = data
        
    do {
        try context.save()
        print("Image is saved")
    } catch {
        print(error.localizedDescription)
    }
}

func fetchImage() -> [Info] {
    var fetchingImage = [Info]()
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Info")
    
    do {
        fetchingImage = try context.fetch(fetchRequest) as! [Info]
    } catch {
        print("Error while fetching the image")
    }
    
    return fetchingImage
}






}

UEU5a

Looks like you are missing error checks on the code. Optional instructions may return a nil value, and should be ideally checked with a conditional block that allows further usage to continue. This will also help you find the specific place where your code is returning a nil and handle it properly.

Can you show me in code?

Most of the time you want to use the ! operator when casting or invoking methods on potentially nil values. That is because by using the ! operator, you are indicating that will unwrap never fail. In this case, loading an image can fail, as it did in your code.

In other words:

		print("core data number is : ", arr[jake].img!.count)

Should be more like:

		print("core data number is : ", arr[jake]?.img?.count ?? 0)

or

		if let counted = arr[jake]?.img?.count  {
			print("core data number is : ", counted)
		}

I don’t know what the Info class is like, so I’m taking some guesses there, the point is to safely unwrap. Inside of fetchImage you see more of the same. If you ship this out in an application, it won’t nice for a user to just see a crash, you want to handle errors a bit.

This topic was automatically closed after 166 days. New replies are no longer allowed.