Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 269
lfalkau Avatar asked Feb 25 '26 06:02

lfalkau


2 Answers

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

like image 132
Krunal Nagvadia Avatar answered Feb 26 '26 20:02

Krunal Nagvadia


you can convert images to string and store them in the core data.

self.selectedImage?.jpegData(compressionQuality: 1)?.base64EncodedString()

and load images from core data with this code

 if let decodedData = Data(base64Encoded: todo.img as! String, options: .ignoreUnknownCharacters) {
   let image = UIImage(data: decodedData)
   Image(uiImage: image!)}
like image 32
Halis Bilal Kara Avatar answered Feb 26 '26 20:02

Halis Bilal Kara