In this tutorial you learn how to do the following:

  1. Create subscription with a notification
  2. Register for a push notification
  3. Fetch and display the new record in the mainView’s textView
caution Code presented on this page assume you are using Xcode 6.4 and Swift version 1.2. So if you are using a newer version of Swift, it may produce errors. Fix them by using Xcode’s Fix-it tool. I assume you are a registered member of Apple’s iOS Developer Program, and you have a real iPhone/iPad device to test the CloudKit code presented here.

A CloudKit Subscription is a mechanism that notifies the app user when these events occurred in the CloudKit private or public database: Record created, record updated, and record deleted. A subscription sends a normal notification. You, the app developer must convert it to a CloudKit notification; so you can access the record or records associated with the notification. A CloudKit subscription can be created both in code and the CloudKit Dashboard. You can attach a notificationInfo to the subscription and you can customize it. For example, you can add an image, a sound, text, etc. When the notification is pushed to the user, she will experience that behavior. You can feed the subscription a combinations of these options:

  • FiresOnce – This option causes the subscription to be deleted from the server after it has fired for the first time.
  • FiresOnRecordCreation – This option indicates that the user is to be notified whenever a new record of a specific type is added to the database.
  • FiresOnRecordDeletion – This option indicates that the user is to be notified whenever a record of a specific type is deleted from the database.
  • FiresOnRecordUpdate – This option indicates that the user is to be notified whenever a record of a specific type is updated in the database.

This image shows how the CloudKit subscription works when the user creates a record in the CloudKit database. The same steps are executed when the user updates or deletes a record in the database.

how-cloudkit-subscription-works

Create a Subscription with a Notification

The following code create and save a subscription with a notification in the CloudKit’s private database. Enter it in the MainViewController.swift file’s executeCodeButtonClicked() function:

@IBAction func executeCodeButtonClicked() {
    // Put the CloudKit private database in a constants
    let privateDatabase = CKContainer.defaultContainer().privateCloudDatabase

    // Create subscription and set three of its properties (an id, a predicate, and options)
    let friendsSubscription = CKSubscription(recordType: "Friends",
        predicate: NSPredicate(format: "TRUEPREDICATE"),
        subscriptionID: "abc123",
        options: .FiresOnRecordCreation)

    // Create a notification and set two of its properties (alertBody and shouldBadge)
    let notificationInfo = CKNotificationInfo()
    notificationInfo.alertBody = "New record added in the database"
    notificationInfo.shouldBadge = false

    // Attach the notification to the subscription
    friendsSubscription.notificationInfo = notificationInfo

    // Save the subscription in the private database
    privateDatabase.saveSubscription(friendsSubscription) {recordReturned, error in
        // On the main thread, display an error/success message in the textView
        if error != nil {
            NSOperationQueue.mainQueue().addOperationWithBlock {
                self.textView.text = "Cloud error\n\(error.localizedDescription)"
            }
        } else {
            NSOperationQueue.mainQueue().addOperationWithBlock {
                self.textView.text = "The subscription record was inserted in the private database."
            }
        }
    }
}

Above code is pretty straight forward; however, there are two things I want say about it:

1. The subscriptionID property you set for the friendsSubscription prevents the saveSubscription() function from returning an error, when you click the Execute Code button more than once.

2. The options property you set for the friendsSubscription object tells the app when to trigger the push notification.

Now, run the app in the iPhone 6 Simulator and click the “Execute Code” button. You will see this message on the sim’s screen:

The subscription record was inserted in the private database.

In the CloudKit Dashboard, verify that above code created the subscription in the database. As you can see in the image below, the code created a subscription of type “Friends” in the database.  The Trigger field was set to INSERT. This mean a push notification is triggered when the user adds a new record in the private database.

cloudkit-figure5-12

Register for a Push Notification

Simply adding a subscription in the database won’t trigger the push notification. You’ll have to add this code in the AppDelegate.swift file’s didFinishLaunchingWithOptions() function to register for push notifications. When you finishing entering the code in class file, run the app in the iPhone 6 Simulator. You’ll see the alert view shown below. Click the OK button; thus give the app permission to send you notifications.

cloudkit-figure5-13

Fetch and Display The New Record

Now that the user have given the app permission to send her notifications, you have to add code in the CloudKitGuide project to fetch and display the new record in the main view’s textView. This image shows the process from the app user’s perspective.

cloudkit-figure5-15

Here’s the code to fetch and display the new record in the main view’s textView.

cloudkit-figure5-14

Here is the code to implement the function that’s called in on code line 55, in above image. Enter it in the MainViewController.swift file.

func fetchAndDisplayNewRecord(recordID: CKRecordID) {
  let privateDatabase = container.privateCloudDatabase
  privateDatabase.fetchRecordWithID(recordID) {newRecord, error in
    if error != nil {
      NSOperationQueue.mainQueue().addOperationWithBlock {
        self.textView.text = "Fetch new record error: \(error.localizedDescription)"
      }
    } else {
      NSOperationQueue.mainQueue().addOperationWithBlock {
        let dbFirstName = newRecord.objectForKey("firstName") as! String
        let dbLastName = newRecord.objectForKey("lastName") as! String
        self.textView.text = "First Name\n" + dbFirstName + "\nLast Name\n" + dbLastName
      }
    }
  }
}

Next, hook up your iPhone or iPad device to your iMac and run the CloudKitGuide application on it. When you see the “Hello user!” message in the textView; send the app to the background, by clicking the device’s Home button. Now, go to the CloudKit Dashboard and select “FriendsZone” in the first column, click the + button located at the top of the third column. Enter Sara in the firstName field, enter Caban in the lastName field. The CloudKit Dashboard should now look like this:

cloudkit-figure5-16

Now, click the Save button in the CloudKit Dashboard. An alert notification will appear on your iPhone/iPad device’s screen. Click it before it disappear.

cloudkit-figure5-17

By clicking the alert notification, the app is brought to the foreground. The new record you entered in the CloudKit’s private database is shown in the main view’s textView:

cloudkit-figure5-18

That’s it! Comments are welcomed! 🙂

Tags:

2 Responses

  1. Hello,

    Great tutorial! I wondering if could create record type through program and subscribe users to that record type for some time which is part of functionality, can I achieve that? or its not possible in production environment?

    • Oh, Hello! In 3 years ago u have the same doubts that I have now.
      I want to implement users create account and login authentication using CloudKit.

      That’s possible?

      Thanks!!!

Leave a Reply

UIDocument Demystified: A Step-by-step Guide on Local and iCloud Document Storage

 

Archives