Home Ask Login Register

Developers Planet

Your answer is one click away!

Matt Mac February 2016

How do I fetch all CloudKit Records created by the current user?

Say I have a 'Species' Record Type that contains Public Records which were created by a number of Users. Currently, my query retrieves all records of 'Species':

private func fetchSpecies() {
    // Fetch Public Database
    let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase

    // Initialize Query
    let query = CKQuery(recordType: "Species", predicate: NSPredicate(format: "TRUEPREDICATE"))

    // Configure Query
    query.sortDescriptors = [NSSortDescriptor(key: "latinName", ascending: true)]

    // Perform Query
    publicDatabase.performQuery(query, inZoneWithID: nil) { (records, error) -> Void in
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        // Process Response on Main Thread
        self.processResponseForQuery(records, error: error)

How can I only fetch records that were created by the current user (as in the owner of the device)?

Thank you!


Allen February 2016

Each CKRecord has a creatorUserRecordID property; therefore, you can try to get owner's userRecordID first. Then, have it into NSPredicate.

let container: CKContainer = CKContainer.defaultContainer()
let completionHandler: (CKRecordID?, NSError?) -> Void = { (userRecordID: CKRecordID?, error: NSError?) in
    if let userRecordID = userRecordID {
        let predicate = NSPredicate(format: "creatorUserRecordID == %@", userRecordID)
        let query = CKQuery(recordType: "Species", predicate: predicate)
        query.sortDescriptors = [NSSortDescriptor(key: "latinName", ascending: true)]
        container.publicCloudDatabase.performQuery(query, inZoneWithID: nil) { (records, error) -> Void in

//// Returns the user record ID associated with the current user.

Post Status

Asked in February 2016
Viewed 3,019 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life