如何从CloudKit容器中删除?

时间:2018-11-15 19:38:29

标签: ios swift tableview cloudkit

最近我已经在应用程序内部实现了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: { $0.creationDate! > $1.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")

    }
}

1 个答案:

答案 0 :(得分:1)

您不能将String传递给deleteCloudData,需要传递一个特定的字符串值-给定索引路径的记录ID将是我的猜测,这取决于您要执行的操作。 / p>

获取索引路径的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")
    }
}