iOS CloudKit Saving data to CloudKit

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


To save date to CloudKit, we must make:

  • A CKRecordID (the key of your unique record)
  • A CKRecord (which includes data)

Making a record key

To ensure that every new record identifier is unique, we use the current timestamp, which is unique. We get the timestamp using NSDate's method timeIntervalSinceReferenceDate(). It is in form of ###.### (# are numbers), which we will use the integer part. To do this, we split the string:


let timestamp = String(format: "%f", NSDate.timeIntervalSinceReferenceDate())
let timestampParts = timestamp.componentsSeparatedByString(".")
let recordID = CKRecordID(recordName: timestampParts[0])

Making the record

To make the record, we should specify the record type (explained in Using CloudKit Dashboard) as Users, the ID as the thing we made just now and the data. Here, we will add a sample text, a picture and the current date to the record:


let record = CKRecord(recordType: "Users", recordID: recordID)
record.setObject("Some Text", forKey: "text")
record.setObject(CKAsset(fileURL: someValidImageURL), forKey: "image")
record.setObject(NSDate(), forKey: "date")


CKRecord *record = [[CKRecord alloc] initWithRecordType: "Users" recordID: recordID];
[record setObject: "Some Text" forKey: "text"];
[record setObject: [CKAsset assetWithFileURL: someValidImageURL] forKey: "image"];
[record setObject: [[NSDate alloc] init] forKey: "date"];


Here, we didn't add the UIImage directly to the record, because as mentioned in Remarks, image format isn't directly supported in CloudKit, so we have converted UIImage into CKAsset.

Accessing the container


let container = CKContainer.defaultContainer()
let database = container.privateCloudDatabase // or container.publicCloudDatabase

Saving the records to CloudKit database


database.saveRecord(record, completionHandler: { (_, error) -> Void in
    print(error ?? "")

Got any iOS Question?