save a image into binary data by creating a image object

408 Views Asked by At

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")

        
        
        
     
       
    }
    
    
}
1

There are 1 best solutions below

0
Duncan C On

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.