jazzedge
11/29/2017 - 5:20 PM

Swift - CloudKit: Fetching Records

There are two main ways of accessing records in CloudKit: Fetching individual records by record ID or using a query with a predicate to get a list of records. In order to fetch records by identifier you need to create a CKRecordID object and then call the fetchRecordWithID: method. In order to fetch records by predate you have to create an NSPredicate object that you can then use with a CKQuery object. You then use this query object to perform a query on the database.

01. Using a query with a predicate to get a list of records. 

let privateDB = CKContainer.defaultContainer().privateCloudDatabase
let predicate = NSPredicate(format: "firstName = %@", "John")
let query = CKQuery(recordType: "Artist", predicate: predicate)
privateDB.performQuery(query, inZoneWithID: nil) { records, error in
   guard let records = records else { return }
   //Use the records..
}

02. Alternative query with a predicate to get a list of records. 

var publicDatabase: CKDatabase? = CKContainer.default().publicCloudDatabase
var predicate = NSPredicate(format: "title = %@", "Santa Cruz Mountains")
var query = CKQuery(recordType: "Artwork", predicate: predicate)
publicDatabase?.perform(query, inZoneWith: nil, completionHandler: {(_ results: [Any], _ error: Error?) -> Void in
    if error != nil {
        // Error handling for failed fetch from public database
    }
    else {
        // Display the fetched records
    }
})

03. Fetching individual records by record ID (the identifier)

let privateDB = CKContainer.defaultContainer().privateCloudDatabase
let artistID = CKRecordID(recordName: "16EBF80D-E59B-4966-B6D5–790E6D79E4D1")
privateDB.fetchRecordWithID(artistID) { record, error in
    guard error == nil else { return }
    //Use the records..
}

04. Alternative, fetching individual records by record ID (the identifier)

var publicDatabase: CKDatabase? = CKContainer.default().publicCloudDatabase
var artworkRecordID = CKRecordID(recordName: "115")
publicDatabase?.fetch(withRecordID: artworkRecordID, completionHandler: {(_ artworkRecord: CKRecord, _ error: Error?) -> Void in
    if error != nil {
        // Error handling for failed fetch from public database
    }
    else {
        // Display the fetched record
    }
})