I want to save a UIImage in CoreData, for that I created a save function with two parameters one for string type and second for image of type "Data". I'm unable to figure out how to covert this into "data"
import UIKit
import CoreData
protocol addDataVCDelegate: class {
func updateInTable(person: Person?)
}
class addDataViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var pName: UITextField!
@IBOutlet weak var imageView: UIImageView!
//MARK: 2 creating a delegate property
weak var delegate: addDataVCDelegate?
override func viewDidLoad() {
super.viewDidLoad()
pName.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
_ = textField.text
return true
}
@IBAction func addData(_ sender: UIButton) {
delegate?.updateInTable(person: self.save(name: pName.text, image: UIImageView.data )) .
dismiss(animated: true, completion: nil)
}
@IBAction func addPhoto(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: {(action:UIAlertAction) in
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: {(action:UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// Code here
imageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
// imageView.image = image
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
picker.dismiss(animated: true, completion: nil)
}
//To save data in Person
func save(name: String?, image: Data) -> Person?{
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return nil
}
// 1
let managedContext =
appDelegate.persistentContainer.viewContext
// 2
let entity =
NSEntityDescription.entity(forEntityName: "Person",
in: managedContext)!
let person = NSManagedObject(entity: entity,
insertInto: managedContext)
// 3
person.setValue(name, forKeyPath: "name")
person.setValue(image, forKeyPath: "image")
// 4
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
return person as? Person
}
}