Reputation: 23616
I'm trying to get values for a user based on their username. I am able to get the correct user using:
class func getByUsername(username: String, callback: (records: [CKRecord]) -> ()){
getSummary(NSPredicate(format: "Username == %@", username)){(records: [CKRecord]) -> Void in
callback(records: records)
}
}
class func getSummary(predicate: NSPredicate, callback: (records: [CKRecord]) -> ()){
let query = CKQuery(recordType: "UserInfo", predicate: predicate)
let queryOperation = CKQueryOperation(query: query)
queryOperation.desiredKeys = ["ID"]
var records = [CKRecord]()
queryOperation.recordFetchedBlock = {record in records.append(record)}
queryOperation.queryCompletionBlock = {_ in callback(records: records)}
CKContainer.defaultContainer().publicCloudDatabase.addOperation(queryOperation)
}
and I am then able to get the correct record by calling:
getByUsername("Username"){(records: [CKRecord]) -> Void in
var record: CKRecord = records[0]
}
and I can also get the correct ID by using
var id: String = record.recordID.recordName
So I know for a fact that I am fetching the correct record, but, when I try to get values from the record, such as the user's email, nil
is returned:
var email: String = record.objectForKey("Email") as String
I've also tried:
record.valueForKey("Email")
record.valueForKeyPath("Email")
When I print record.allKeys()
, I get an empty array, []
, and when I print record.allTokens()
, I get a return of nil
Am I not fetching a value from the record correctly, or do I have to query the database for every single value that I would like to get using the record ID? Based on what the documentation says:
A CKRecord object is a dictionary of key-value pairs that you use to fetch and save the data of your app.
I would assume that I do not have to query the database for every value that I would like to get, and that the values are automatically inserted into the CKRecord
upon getting it from iCloud
Upvotes: 5
Views: 4351
Reputation: 13127
When you leave out the line:
queryOperation.desiredKeys = ["ID"]
the query will return all the fields.
That you did not receive the ID field is probably because its a system field which can be accessed using
var ID = record.recordID.recordName
Upvotes: 4