Topics

#31: CloudKit Operations ⛅️🏥

Topics

Diving deeper into CloudKit today we'll look at some more advanced ways of interacting with your app's data using operations. CloudKit's NSOperation-based API allows for things like batch saves/changes, ‘paging' through data and more.

Here's a few of the things you can do:

Advanced Querying

let predicate = NSPredicate(value: true)
let query = CKQuery(
  recordType: "Spaceship", 
  predicate: predicate
)

let operation = CKQueryOperation(query: query)

operation.desiredKeys = ["topSpeed", "name"]
operation.resultsLimit = 30

let container = CKContainer.defaultContainer()
let publicDB = container.publicCloudDatabase

publicDB.addOperation(operation)

Batch Saves/Changes

Here I'm using CKModifyRecordsOperation to seed my app with example data during development.

var objects = [Spaceship]()

for i in 0...100 {
  objects.append(Spaceship(
    name: "Test Spaceship"
  ))
}

let operation = CKModifyRecordsOperation(
  recordsToSave: objects.map { $0.toRecord() },
  recordIDsToDelete: nil
)

publicDB.addOperation(operation)

Paging

CKQueryOperation‘s queryCompletionBlock provides an optional CKQueryCursor. You can store this and supply it to your next query to load the next logical 'page' of records.

Progress

One of the great things about CKModifyRecordsOperation and CKQueryOperation is their ability to report progress at a per-record level.