AvaJ AvaJ - 11 months ago 51
Swift Question

swift core data: save images from camera

I use Swift and I'm working on an app that has a "Camera" button. If I click on this button the iPhone camera opens. But, when I go to "Use Photo" the app doesn't work.

How can I save shot images in an array, so that they are listed in a


func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete{


You are setting the image to the imagePicker instance, which will not work properly. Instead, you want to:

  1. Serialize the image to an NSData object
  2. Store the NSData object in the database
  3. Read each image back from the database in the TableView's data source To get the NSData object, you could convert the image to PNG. You should put something like this in your didFinishPickingImage delegate function:

    let imgData = UIImagePNGRepresentation(image) item.setValue(imgData, forKey: "image") The above code assumes your data model has a column with type Data and name image. It will then insert the converted image into the database.

Now, in your tableViewDelegate's cellAtRowForIndexPath, read each image's data from the database and put them in cells, using something like this: cell.imageView.image = UIImage(data: imgData)

However, I would not recommend this approach for storing full-resolution photos. Core Data is designed for relatively small values, not full resolution images. It's better to store the images in the file system (app's document folder) with a standardized naming convention.