CloudKit in context

Nofel
2 min readJun 26, 2015

--

I have been playing with CloudKit for a while now. I admit that I was always skeptical because of the things being said and discussed in the developer community. Specially a thread on news.ycombinator in which the take away thing was that Apple has a very bad reputation in doing the server side stuff. And who doesn’t agree because who hasn’t been bitten by the iCloud Sync claims like “It Just Works” while actually being “It does work sometimes but only if you are the chosen one”.

While with CloudKit Apple is trying to fix their past mistakes. I have tried it and it works. It’s Apis are very well done and documented. And the ease with which you can incorporate it in your apps is mind blowing.

I come from being working on CoreData a lot and I personally like how its Api is designed. So, while working on CloudKit I missed some features which CoreData’s Api provide like the NSManagedObjectContext class. What it does is it tracks all the insertions, deletions and modifications on instances of NSManagedObject class and it simply commits the changes to the store only when we call save() on an instance of it.

Allow me to introduce CKSRecordContext

I tried to implement the same approach with CloudKit. I wrote a class CKSRecordContext. It does for CKRecord what NSManagedObjectContext does for NSManagedObject. It tracks all the insertions, modifications and deletions and only tries to save the instances of CKRecords on the server when we call save() on an instance of it.

Time to show some code in Swift !

Creating a new instance of CKSRecordContext

var context:CKSRecordContext = CKRecordContext(database: CKContainer.defaultContainer().privateCloudDatabase, recordZone: nil)

Creating a new CKRecord

var ckRecord = context.insertNewCKRecord("NewRecordType")

Modifying CKRecords

Good news ! No code over here. Any changes in the records created with the methods provided by the context are tracked automatically.

Deleting a CKRecord

var ckRecord = context.insertNewCKRecord("NewRecordType")
context.deleteRecord(record: ckRecord)

Fetching CKRecords from the server

fetchCKRecord(recordID:CKRecordID,completion:(record:CKRecord?,error:NSError!) ->())fetchCKRecords(recordType:String,predicate:NSPredicate,completion:(results:Array<AnyObject>?,error:NSError!) ->())
fetchCKRecords(recordType:String,predicate:NSPredicate,sortDescriptors:[NSSortDescriptor],completion:(results:Array<AnyObject>?,error:NSError!) ->())

And Finally ! Saving the Insertions, Modifications and Deletions to server.

Its a one liner ! (Ignoring the completion closure to make it sound cooler :)

context.save { error in
if error != nil {
print("Saved Successfully")
}
}

For more info Check it out on Github.

Happy CloudKitting :)

--

--