Skip to content

Instantly share code, notes, and snippets.

@ameseee
Created August 3, 2018 12:45
Show Gist options
  • Select an option

  • Save ameseee/ef27bc83e38039b82b0d17a11283c82f to your computer and use it in GitHub Desktop.

Select an option

Save ameseee/ef27bc83e38039b82b0d17a11283c82f to your computer and use it in GitHub Desktop.

ADD/SAVE PHOTO TAPPED

//create a new item in CD, save to CD, pop back to VC
//get context 

if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
  let photoToBeSaved = Photo(entity: Photo.entity, insertInto: context)
  photoToBeSaved.imageCaption = textFieldData.text!
  
  //image is save as DATA not a UIImage, so we have to do a conversion here to change data types:
  
  if let userImage = imageView.image {
    //convert it into data 
    if let userImageData = UIImagePNGRepresentation(userImage) {
      photoToBeSaved.imageData = userImageData
    }
  }
  
  //save context 
  (UIApplication.shared.delegate as? AppDelegate)?.saveContext()
  
  //send user back to table view screen
  navigationController.popViewController(animated: true)
  

GET ITEMS OUT OF CORE DATA IN TABLE VC

//write a getPhotos function

func getPhotos() {
  if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
    if let coreDataPhotos = try? context.fetch(Photo.fetchRequest) as? [Photo] {
      if let unwrappedCoreDataPhotos = coreDataPhotos {
        // this is where we want to save to VC. Create an instance variable in VC: 
        // var photos : [Photo] = []
        photos = unwrappedCoreDataPhotos
        tableView.reloadData()
      }
    }
  }
}

ADD IN A VIEW WILL APPEAR INTO TABLE VC

override func viewWillAppear(_ animated: Bool) {
  getPhotos()
}

NOW, CELL FOR ROW AT INDEX PATH

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    
    //we need access to the current item we are working with
    let cellItem = photos[indexPath.row]
    
    cell.textLabel?.text = cellItem.title
    
    if let cellItemImageData = cellItem.imageData {
      if let cellItemIamge = UIImage(data: cellItemImageData) {
          cell.imageView?.image = cellItemImage
      }
    }

    return cell
}

LAST STEP: COMMIT EDITING STYLE IN ADD PHOTO VC

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
      if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
        let photoToDelete = photos[indexPath.row]
        context.delete(photoToDelete)
        
        (UIApplication.shared.delegate as? AppDelegate)?.saveContext()
        
        getPhotos()
      }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment