Topics

#26: CloudKit Basics ⛅

Topics

CloudKit is Apple's API for storing and retrieving data from iCloud. With the recent introduction of the CloudKit Web Services API as well as CloudKit JS, CloudKit is now a very attracive option for the backend of your next app.

Let's take a look at the very basics of using CloudKit to create, retrieve, update and delete records:

Creating a Record

let publicDB = CKContainer.defaultContainer().publicCloudDatabase

let spaceshipRecord = CKRecord(recordType: "Spaceship")
spaceshipRecord["model"] = "T-16"
spaceshipRecord["maxSpeed"] = 1200 // in km

publicDB.saveRecord(spaceshipRecord) { (record, error) in }

Retrieving Records

let query = CKQuery(
  recordType: "Spaceships",
  predicate: NSPredicate(format: "maxSpeed > 500")
)

publicDB.performQuery(query, inZoneWithID: nil) { (records, error) in }

Updating Records

spaceshipRecord["maxSpeed"] = 1500

publicDB.saveRecord(spaceshipRecord) { (record, error) in }

Deleting Records

publicDB.deleteRecordWithID(spaceshipRecord.recordID) {
  (recordID, error) in }