-2

In my swift code the goal is to save a image into core data. My code right now is not working. Its not the right type. The code works if it is a string but trying to save it to binary data is not working. I tried creating a UIImage object and it is not working. Core data binary is called "pic"

import UIKit;import CoreData

class ViewController: UIViewController {
    
   
    
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let co = UIImage(named: "a.png")
        
        let entityA = NSEntityDescription.insertNewObject(forEntityName: "Info" , into: context)
       
        entityA.setValue(co,forKey: "pic")

        
        
        
     
       
    }
    
    
}
jj smith
  • 49
  • 4

1 Answers1

0

I haven't worked with Core Data for quite a while, but you almost certainly want to serialize your image as Data and then save it as a BLOB (Binary Large Object).

You should be able to use the UIImage pngData() function to convert it to data.

Check out this tutorial for more details.

Duncan C
  • 128,072
  • 22
  • 173
  • 272