我想在 CoreData 中保存 UIImage,为此我创建了一个保存函数,其中包含两个参数,一个用于字符串类型,第二个用于“数据”类型的图像。我无法弄清楚如何将其转换为“数据”
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
}
}