func savePhotoToCoreData(image: UIImage) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Photo", in: managedContext)!
let photo = NSManagedObject(entity: entity, insertInto: managedContext) as! Photo
if let imageData = image.pngData() {
photo.imageData = imageData
}
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
func fetchPhotoFromCoreData() -> UIImage? {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return nil
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Photo")
do {
let results = try managedContext.fetch(fetchRequest) as! [Photo]
if let firstPhoto = results.first, let imageData = firstPhoto.imageData {
return UIImage(data: imageData)
} else {
return nil
}
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
return nil
}
}