如何从 CloudKit 容器中删除?

How can I Delete from a CloudKit container?

最近我在我的应用程序中实现了 CloudKit,我可以成功地将数据保存在 CloudKit 上并将其显示在 TableView 中。问题是我无法从容器中删除单个数据。 这是我使用的代码:

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: { [=11=].creationDate! > .creationDate! })
        self.quotesSavedOnCloud = sortedRecords
        DispatchQueue.main.async {
            self.tableView.refreshControl?.endRefreshing()
            self.tableView.reloadData()
        }
    }
}

下面是我希望能够通过滑动删除数据的代码部分:

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")

    }
}

您不能将 String 传递给 deleteCloudData,您需要传递特定的字符串值 - 给定索引路径的记录 ID 是我的猜测,因为您正在尝试执行此操作.

获取索引路径的 CKRecord(就像在 cellForRowAt 中所做的一样),并获取其 recordID.

顺便说一句,您的 deleteCloudData 使用 CKRecord.ID 而不是 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")
    }
}