Reputation: 27
Recently I've implemented CloudKit inside my app, I can successfully save the data on CloudKit and show it inside a TableView. The problem is that I can't remove the single data from the container. Here's the code I use:
let database = CKContainer.default().privateCloudDatabase
var notes = [CKRecord]()
func saveToCloud(note: String) {
let newQuote = CKRecord(recordType: "Note")
newQuote.setValue(note, forKey: "content")
database.save(newQuote) { (record, error) in
guard record != nil else { return }
print("saved record")
}
}
@objc func queryDatabase() {
let query = CKQuery(recordType: "Note", predicate: NSPredicate(value: true))
database.perform(query, inZoneWith: nil) { (records, _) in
guard let records = records else { return }
let sortedRecords = records.sorted(by: { $0.creationDate! > $1.creationDate! })
self.quotesSavedOnCloud = sortedRecords
DispatchQueue.main.async {
self.tableView.refreshControl?.endRefreshing()
self.tableView.reloadData()
}
}
}
And here's the part of the code that I want to be able to delete data with a swipe:
func deleteCloudData(recordName: String) {
let recordID = CKRecord.ID(recordName: recordName)
database.delete(withRecordID: recordID) { (id, error) in
if error != nil {
print(error.debugDescription)
}
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
deleteCloudData(recordName: String)
print("Data delated successfully")
}
}
Upvotes: 0
Views: 500
Reputation: 318774
You can't pass String
to deleteCloudData
, you need to pass a specific string value - the record id for the given index path would be my guess given what you are trying to do.
Get the CKRecord
for the index path (just like are doing in cellForRowAt
), and get its recordID
.
BTW, it would make more sense for your deleteCloudData
to take a CKRecord.ID
and not a String
.
func deleteCloudData(recordID: CKRecord.ID) {
database.delete(withRecordID: recordID) { (id, error) in
if error != nil {
print(error.debugDescription)
}
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
deleteCloudData(recordID: quotesSavedOnCloud[indexPath.row].recordID)
print("Data delated successfully")
}
}
Upvotes: 1