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()
}
}
}