iosswiftuitableviewcloudkitckrecord

What is a robust approach to deleting a CKRecord associated with an IndexPath in a table view or collection view?


Basically to delete the cell "offline" I use this method so that whenever you swipe from right to left the user can delete the tableview cell.

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == .delete) {
        self.polls.remove(at: indexPath.row)
    }
}

However, it obviously doesn't affect the CKRecord of the cell content I created before. So how can I fetch and delete the CKRecord data at the exact row the user swiped-to-delete on?


Solution

  • Assuming polls is the data source array declared as [CKRecord] you have to do three things.

    1. Get the record from the data source array at the given index and remove it from the appropriate CKDatabase.
    2. Remove the record from the data source array (you're already doing that).
    3. Delete the row in the table view calling deleteRowsAtIndexPaths passing [indexPath].

    For example (publicDatabase is the actual CKDatabase instance):

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
           let record = polls[indexPath.row]
           publicDatabase.deleteRecordWithID(record.recordID, completionHandler: ({returnRecord, error in
              // do error handling
           })
           polls.removeAtIndex(indexPath.row)
           tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }
    }
    

    Edit:

    For proper error handling you might have to put the code of step two and three into the completion block.

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
           let record = polls[indexPath.row]
           publicDatabase.deleteRecordWithID(record.recordID, completionHandler: ({returnRecord, error in
              if error != nil {
                 // do error handling
              } else {
                 self.polls.removeAtIndex(indexPath.row)
                 dispatch_async(dispatch_get_main_queue()) {
                    self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
                 }
              }
           })
        }
    }