Skip to content

Instantly share code, notes, and snippets.

@tinyhappysteps
Last active October 5, 2015 15:40
Show Gist options
  • Save tinyhappysteps/2e10556c1e51f8b00ed2 to your computer and use it in GitHub Desktop.
Save tinyhappysteps/2e10556c1e51f8b00ed2 to your computer and use it in GitHub Desktop.
Save and Fetch Private DB in CloudKit
// Don't forget to set capabilities to iCloud on, Cloudkit
import UIKit
import CloudKit
class ViewController: UIViewController {
let database = CKContainer.defaultContainer().privateCloudDatabase
enum CarType: String{
case Estate = "Estate"
}
func recordId() -> CKRecordID{
var recordName = "hi"
return CKRecordID(recordName: recordName)
}
func saveRecordWithCompletionHandler(completionHandler:
(succeeded: Bool, error: NSError!) -> Void){
let volvoV50 = CKRecord(recordType: "MyCar", recordID: recordId())
volvoV50.setObject(2015, forKey: "year")
database.saveRecord(volvoV50, completionHandler: {
(record: CKRecord?, error: NSError?) in
completionHandler(succeeded: (error == nil), error: error)
})
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
print("Fetching the record to see if it exists already...")
database.fetchRecordWithID(recordId(), completionHandler:{
(record: CKRecord?, error: NSError?) in
if error != nil{
print("An error occurred")
if error!.code == CKErrorCode.UnknownItem.rawValue{
print("This error means that the record was not found.")
print("Saving the record...")
self.saveRecordWithCompletionHandler{
(succeeded: Bool, error: NSError!) in
if succeeded{
print("Successfully saved the record")
} else {
print("Failed to save the record. Error = \(error)")
}
}
} else {
print("I don't understand this error. Error = \(error)")
}
} else {
print("Seems like we had previously stored the record. Great!")
print("Retrieved record = \(record)")
guard let record = record else {
print("The record is nil")
return
}
/* Now make your changes to the record */
record.setValue(2016, forKey:"year")
self.database.saveRecord(record, completionHandler:
{(record:CKRecord?, error: NSError?) in
if error == nil{
print("Successfully modified the record")
} else {
print("Failed to modify the record. Error = \(error)")
}
})
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment