我正在构建一个应用程序,允许用户从公共商店上传/下载信息。我认为cloudKit存储将是理想的。
我希望用户能够通过KeyWord字段搜索商店中的记录,然后在选择一个记录时下载整个记录。
在SQL术语中,这将是:
SELECT id,KeyWords from myDB WHERE KeyWords LIKE %searchstring%
其次是:
SELECT * FROM myDB WHERE id = selectedID
我一直在使用此代码模式从cloudKit存储中检索记录:
var publicDatabase: CKDatabase?
let container = CKContainer.defaultContainer()
override func viewDidLoad() {
super.viewDidLoad()
publicDatabase = container.publicCloudDatabase
}
func performQuery(){
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Library", predicate: predicate)
publicDatabase?.performQuery(query, inZoneWithID: nil,
completionHandler: ({results, error in
...
[code to handle results / error here]
...
})
}
但是这会返回所有每条记录的内容,这是很多不必要的信息。
我只想从cloudkit记录中获取单个字段。
有没有一种简单的方法可以做到这一点,是否有人有代码片段?
CKFetchRecordsOperation允许下载受限制的列,但要求您知道要下载的记录的ID。
答案 0 :(得分:1)
为此,您可以在CKQueryOperation上使用desiredKeys属性。有关详细信息,请参阅:desiredkeys documentation
答案 1 :(得分:0)
确定有用的东西。这可能是hacky,但是我在相同的情况下为其他任何人提供信息......
let predicate = NSPredicate(value: true) // returns all - replace with whatever condition you want
let query = CKQuery(recordType: "Library", predicate: predicate) // create a query using the predicate
var operation = CKQueryOperation(query: query) // create an operation using the query
operation.desiredKeys = ["KeyWords"] // Array of whatever 'columns' you want to return
// operation.resultsLimit = 15 // optional limit on records
// Define a closure for what to do for each returned record
operation.recordFetchedBlock = { [weak self] (record:CKRecord!) in
// Do whatever you want with each returned record
println(record.objectForKey("KeyWords"))
}
// Define a closure for when the operation is complete
operation.queryCompletionBlock = { [weak self] (cursor:CKQueryCursor!, error:NSError!) in
if cursor != nil {
// returns the point where the operation left off if you want t retrieve the rest of the records
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// Do what you want when process complete
self!.tableView.reloadData()
if error != nil {
println("there was an error")
}
})
}
self.publicDatabase!.addOperation(operation) // Perform the operation on given database