Reputation: 3050
I'm learning to use CloudKit and finally managed to retrieve/query data hard coded into the dashboard. I'm trying to query only one value from a record using a CKQueryOperation
but I always receive all the values in each and every record.
In my code below I'm trying to get just the "age" values by using the desiredKey
property - what I get back is "age", "firstName", "lastName" etc etc.
let container = CKContainer.defaultContainer()
let publicData = container.publicCloudDatabase
// select all records
let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
let query = CKQuery(recordType: "quizRecord", predicate: predicate)
// get just one value only
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["age"]
// addOperation
publicData.addOperation(operation)
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil { // There is no error
// PROBLEM .. this prints out all values ????
print(results)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
})
}
else {
print(error)
}
}
//// The following / amended code works fine
let container = CKContainer.defaultContainer()
let publicData = container.publicCloudDatabase
// select all records
let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
let query = CKQuery(recordType: "quizRecord", predicate: predicate)
// get just one value only
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["age"]
// get query
operation.recordFetchedBlock = { (record : CKRecord) in
// process record
print(record)
}
// operation completed
operation.queryCompletionBlock = {(cursor, error) in
dispatch_async(dispatch_get_main_queue()) {
if error == nil {
print("no errors")
// code here
} else {
print("error description = \(error?.description)")
}
}
}
// addOperation
publicData.addOperation(operation)
Upvotes: 2
Views: 835
Reputation: 318774
The problem is simple. You set the desiredKeys
on the CKQueryOperation
but you never actually use the operation. You instead use performQuery
on the database.
If you to use the operation and limit the data to the specific keys, you need to add the operation to the database (using addOperation:
) instead of calling performQuery
. And of course you need to assign a block to the one or more of the recordFetchedBlock
and queryCompletionBlock
properties of the operation.
let container = CKContainer.defaultContainer()
let publicData = container.publicCloudDatabase
// select all records
let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
let query = CKQuery(recordType: "quizRecord", predicate: predicate)
// get just one value only
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["age"]
operation.recordFetchBlock = { (record : CKRecord) in
// process record
}
operation.queryCompletionBlock = { (cursor : CKQueryCursor!, error : NSError!) in
// Query finished
}
// addOperation
publicData.addOperation(operation)
Upvotes: 2