Emr*_*der 6 field ios swift cloudkit
我只想获取 CloudKit 音乐记录中的 Song_Name 字段。我正在尝试下面的代码,但它仍然获取音乐记录中的所有字段。我想我需要使用 publicDB.add(operation) 方法编译操作,但它不允许我像现在使用 publicDB.perform(query, in....) 那样声明“results”
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Musics", predicate: predicate)
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["Song_Name"]
publicDB.perform(query, inZoneWith: nil) { [unowned self] results, error in
guard error == nil else {
DispatchQueue.main.async {
self.delegate?.errorUpdating(error! as NSError)
print("Cloud Query Error - Refresh: \(error)")
}
return
}
self.items_music.removeAll(keepingCapacity: true)
for record in results! {
let music = Musics(record: record, database: self.publicDB)
self.items_music.append(music)
}
DispatchQueue.main.async {
self.delegate?.modelUpdated()
}
}
}
Run Code Online (Sandbox Code Playgroud)
您正在创建CKQueryOperation并设置操作的desiredKeys属性,但是您没有使用此操作。您只需对数据库执行查询,因此不会使用任何查询操作的属性。
您需要为您的操作分配一个记录获取块和查询完成块,然后将该操作添加到数据库中以实际运行它。
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Musics", predicate: predicate)
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["Song_Name"]
var newItems = [Musics]()
operation.queryCompletionBlock = ( { (cursor, error)->Void in
guard error == nil else {
DispatchQueue.main.async {
self.delegate?.errorUpdating(error! as NSError)
print("Cloud Query Error - Refresh: \(error)")
}
return
}
self.items_music = newItems
DispatchQueue.main.async {
self.delegate?.modelUpdated()
}
})
operation.recordFetchedBlock = ( { (record) -> Void in
let music = Musics(record: record, database: self.publicDB)
newItems.append(music)
})
publicDB.add(operation)
Run Code Online (Sandbox Code Playgroud)
我省略了一些您需要检查cursor提供给完成块的代码。如果不是,nil则您需要发出另一个查询以获取其他项目