ios - 如何从 CloudKit 容器中删除?

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

    }
}

最佳答案

你不能将 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")
    }
}

关于ios - 如何从 CloudKit 容器中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53326804/

相关文章:

iphone - Return 语句创建和释放一个对象

swift - 你能扩展一个枚举吗?

ios - 如何在 JTCalender 中设置日期限制?

ios - SLServiceTypeFacebook' 在 iOS 11.0 中被弃用

ios - 查找表格 View 中所有数字的平均值

ios - 过滤搜索结果

iphone - Flipview 内的 Tableview 使用实用程序模板

ios - 本地通知能否只让apple watch震动不播放声音?

ios - 如何断开已连接的蓝牙设备

ios - 如何发送所有 AFNetworking 请求的通用信息?