I'm trying to convert an image that the user has imported from the camera roll, convert the image to NSData and store it as binary data in CoreData. I have managed to convert it to binary and print it, but I doesn't store the value to core data. I have managed to store strings and other values to different attributes of the entity but for whatever reason the binary data isn't working.
func savingData(savingImage: UIImage){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let userEntity = NSEntityDescription.entity(forEntityName: "Image", in: managedContext)!
let data = savingImage.pngData()! as NSData
if idLabel.text != "" {
let user = NSManagedObject(entity: userEntity, insertInto: managedContext)
user.setValue(idLabel.text, forKeyPath: "id")
user.setValue(descriptionText.text, forKey: "imgdescription")
user.setValue(confidenceLabel.text, forKey: "confidence")
user.setValue(data, forKey: "binary")
do {
try managedContext.save()
dataSaved.text = "Your answers have been saved! Click Home to return."
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
dataSaved.text="Error!"
}
}
}
}
This is the code I have for storing the data. All the values save to core data and these values can be retrieved on the next class.
I've checked all the connections, triple checked that the naming of the entity and attributes and it still won't work.
Does anybody have any idea?
EDIT: the attribute "binary" is stored as 'binary data' in core data
func retrieveData() {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Image")
fetchRequest.fetchLimit = 1
fetchRequest.predicate = NSPredicate(format: "id = %@", valueSelected)
fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "id", ascending: false)]
do {
let result = try managedContext.fetch(fetchRequest)
for data in result as! [NSManagedObject] {
idText.text = data.value(forKey:"id") as? String
descriptionText.text = data.value(forKey:"imgdescription") as? String
confidenceText.text = data.value(forKey:"confidence") as? String
photoView = data.value(forKey:"binary") as? UIImageView
}
} catch {
print("Nothing found.")
}
}
This is how I'm calling it in the other class