Search code examples
iosswiftcore-dataswift4

saving image with Core Data


I'm trying to save a user profile picture with CoreData but don't understand how to proceed.

I know I have to create an entity and I read it have to be BinaryData type, but then I don't understand how to save it and load it.

I tried this way :

let profilePicture = UserPicture(context: AppDelegate.viewContext)
profilePicture.userProfilePicture = profilPictureImageView.image?.pngData()
    try? AppDelegate.viewContext.save()

But doesn't work. I did't find anything clearly enough help me.


Solution

  • For save image in CoreData you must convert the image into DATA type then you can save it into CoreData.This code may useful to save image in CoreData.

    @IBOutlet weak var profileimg: UIImageView?
    
    let data = (profileimg?.image)!.pngData()
    let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
    let newUser = NSEntityDescription.insertNewObject(forEntityName: "Entity", into: context!)
    newUser.setValue(data, forKey: "img")
    
    do {
        try Constant.context?.save()
    }
    

    Make sure the key you enter is correct. Must check box of the Allow External Storage in the Data model Inspector.But I not to recommended to save image in CoreData. Hope this would be helpful.

    enter image description here