保存和获取 CloudKit 引用
Posted
技术标签:
【中文标题】保存和获取 CloudKit 引用【英文标题】:Saving & Fetching CloudKit References 【发布时间】:2018-10-10 14:47:25 【问题描述】:我在使用 CloudKit 参考创建时遇到问题。数据正在保存到 CloudKit 中,但它没有引用其父级(列表)。不知道我做错了什么,任何帮助将不胜感激!
保存方法
var list: CKRecord?
var item: CKRecord?
@objc func save()
let name = nameTextField.text! as NSString
//Fetch Private Database
let privateDatabase = CKContainer.default().privateCloudDatabase
if item == nil
//Create Record
item = CKRecord(recordType: RecordTypeItems)
//Initialization Reference
guard let recordID = list?.recordID else return
let listReference = CKRecord.Reference(recordID: recordID, action: .deleteSelf)
item?.setObject(listReference, forKey: "list")
item?.setObject(name, forKey: "name")
//Save Record
privateDatabase.save(item!) (record, error) in
DispatchQueue.main.sync
self.processResponse(record: record, error: error)
获取方法
var list: CKRecord!
var items = [CKRecord]()
private func fetchItems()
//Fetch Private Database
let privateDatabase = CKContainer.default().privateCloudDatabase
//Initialize Query
guard let recordID = list?.recordID else return
let reference = CKRecord.Reference(recordID: recordID, action: .deleteSelf)
let query = CKQuery(recordType: RecordTypeItems, predicate: NSPredicate(format: "list == %@", [reference]))
//Configure Query
query.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
//Peform Query
privateDatabase.perform(query, inZoneWith: nil) (records, error) in
DispatchQueue.main.sync
self.processResponseForQuery(records: records, error: error)
【问题讨论】:
您的问题不清楚,但是您是否尝试过查看 CloudKit Web 仪表板以查看引用是否已成功保存到服务器上的项目记录中? 【参考方案1】:您在哪里创建查询以检索引用列表的项目,谓词格式字符串中的列表引用是否应该在数组内?如果您创建项目的引用,如 item?.setObject(listReference, forKey: "list")
,CloudKit 将推断 list
字段为单个 CKRecord.Reference
,因此查询将是:
let query = CKQuery(recordType: RecordTypeItems, predicate: NSPredicate(format: "list == %@", reference))
【讨论】:
以上是关于保存和获取 CloudKit 引用的主要内容,如果未能解决你的问题,请参考以下文章
使用 CloudKit 保存尝试对成员“保存(_:completionHandler :)”的模糊引用
swift Swift - CloudKit - 获取添加保存删除多个记录