-1

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
        }


    }
Vollan
  • 1,887
  • 11
  • 26
  • 1
    possible duplicate: https://stackoverflow.com/questions/16685812/how-to-store-an-image-in-core-data answer here https://stackoverflow.com/a/55497196/4757272 – Vollan Aug 05 '19 at 08:28
  • Woa, tagging this question with swift 4.2> and using old core data code? Core data is much more type safe now – J. Doe Aug 05 '19 at 08:45

2 Answers2

3

Better solution to store images is a file system. You save your image to file system with id like a name, and store that id in the core data. To retrieve your image, you get the entity from core data with id, and then you get the image with this id from your file system (usually from documents folder).

Zakhar
  • 59
  • 4
-1

A Swift solution

You could use something like the following

let image = UIImage()//Add your image here
let data = image.pngData() //Returns Data?

Then try saving this data

Make sure you check the "Allow External Storage" option in the data model inspector :).

But I'd recommend not saving image/videos into CoreData