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.
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.
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!)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With