Coder221 Coder221 - 6 months ago 72
Swift Question

How to store image from collectionviewcell to core data

I have an entity called

is an attribute of binary data. I have the following

@IBOutlet weak var collectionView: UICollectionView!
var imageSelected = [UIImage]()

Then I have collection view as follows

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return self.imageSelected.count


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
as! EditCollectionViewCell

cell.imageView?.image = imageSelected[(indexPath as NSIndexPath).row]
cell.layer.borderColor = UIColor.white.cgColor
cell.layer.borderWidth = 3

return cell

Now I am trying to save image to core data when Save bar button item is pressed as follows

@IBAction func saveBtnPressed(_ sender: AnyObject) {

if #available(iOS 10.0, *) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let task = Task(context: context)

task.taskDesc = taskText.text!
//task.taskImage = UIImagePNGRepresentation(cell.imageView?.image)

} else {
// Fallback on earlier versions

I am getting error for taskImage, any help regarding storing image will be appreciated.


My code to store image in core data

let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext

let newContact = NSEntityDescription.insertNewObjectForEntityForName("Contact", inManagedObjectContext: context)
let imageData:NSData = UIImageJPEGRepresentation(imgViewPhoto.image!, 1)!
newContact.setValue(imageData, forKey: "imageData")

and retrieve it from coredata

let imageData:NSData = contact.valueForKey("imageData") as! NSData
imgViewPhoto.image = UIImage(data: imageData, scale: 1)