How to Use Apple’s CloudKit for Push Notifications

Apple introduced their CloudKit framework alongside iOS 8 in 2014. While its main purpose was to act as an online database for iOS applications, CloudKit also offers many other features, including push notifications.

How to Use Apple’s CloudKit for Push Notifications

In this tutorial, I will be showing you how to use the CloudKit framework to implement push notifications for your iOS apps. If you want to learn more about the other features CloudKit has to offer, you can read my tutorial covering the basics of the framework:

  • How to Use Apple's CloudKit for Push Notifications

    An Introduction to CloudKit

    In this tutorial, you will learn how to set up CloudKit for an iOS application. Along the way, you will become familiar with the CloudKit dashboard, the…

This tutorial requires you to be using at least Xcode 8 with Swift 3. You will also need to have a physical iOS device to test with and an Apple developer account so that you can enable CloudKit for your application.

1. Why Use CloudKit?

First, we’ll look at the advantages (and disadvantages) of using CloudKit for your app’s push notifications.

As you will see in this tutorial, to set up push notifications with CloudKit, you don’t need to worry about creating certificates and provisioning profiles as you do with other cloud services. Since everything is made by Apple, all you have to do is enable CloudKit for your app, and the rest just works.

One of the best things about CloudKit for some developers is how much you get for free. Many other Backend-as-a-Service (BaaS) companies exist and offer push notifications for iOS apps, but most of these have limits on how many notifications can be sent for free. With CloudKit, there is no limit on the number of push notifications you can send to your users. However, CloudKit’s free tier does limit data storage, data transfer, and the number of user requests per second.

Another advantage of using CloudKit in your apps is that, being provided by Apple, network stability and maintenance will be something you will never have to worry about. Apple service outages occur very rarely and are fixed promptly. This means that you can rely on CloudKit to always be working properly for your users.

However, a disadvantage you should be aware of when using CloudKit is that it is not currently available on any non-Apple platforms. That means that if you want to create an Android version of your app, CloudKit won’t work. For a cross-platform solution, I would recommend another BaaS such as back4app (built on Parse) as I discuss in this tutorial:

  • How to Use Apple's CloudKit for Push Notifications
    iOS SDK
    Easy iOS Push Notifications With back4app
    Davis Allie

2. Setting Up CloudKit

To begin, create a new project in Xcode from the iOS > Application > Single View Application template.

Once Xcode has created your project, go to the Project navigator and click on the Capabilities tab. On this screen, click the switch to enable iCloud and then enable the CloudKit checkbox:

How to Use Apple's CloudKit for Push Notifications

Once you have enabled CloudKit, you can now go to the CloudKit dashboard for your app.

To send push notifications to our app’s users, we are going to create a GlobalNotification record type which will notify all users when a new record of this type is created. If the Record Type section of the CloudKit dashboard isn’t open already for you after logging in, click on it in the sidebar.

To create a new record type, click on the + button at the top of the screen. Fill in the menu as shown in the following screenshot:

How to Use Apple's CloudKit for Push Notifications

For this tutorial, we are only adding a single content field to the record type, but for your own applications, you can add as many as you need.

When you are done, click on the Save button in the bottom-right corner.

3. Setting Up App

Back in Xcode, open up your AppDelegate.swift file and add the following import statements at the top of your code:

import CloudKit
import UserNotifications

This code will just import the CloudKit and UserNotifications frameworks. We are going to use the UserNotifications to manage both notification permissions and incoming notifications. If you want to learn more about this framework, you can read my tutorial covering it here:

  • How to Use Apple's CloudKit for Push Notifications

    An Introduction to the UserNotifications Framework

    In this tutorial, you will learn about the new UserNotifications framework in iOS 10, tvOS 10, and watchOS 3. This new framework provides a modern set of…

Next, edit your AppDelegate class definition to make it conform to the UNUserNotificationCenterDelegate protocol:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    ...
}

Now we need to request permission to show notifications. To do so, replace your application(_:didFinishLaunchingWithOptions:) method with the following:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { authorized, error in
        if authorized {
            application.registerForRemoteNotifications()
        }
    })
    
    return true
}

With this code, we ask the user for permission to show notifications and if they accept, register the app for push notifications.

Now, we need to implement the application(_:didRegisterForRemoteNotificationsWithDeviceToken:) method. Add the following code to your AppDelegate class:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let subscription = CKQuerySubscription(recordType: "GlobalNotification", predicate: NSPredicate(format: "TRUEPREDICATE"), options: .firesOnRecordCreation)
    
    let info = CKNotificationInfo()
    info.alertBody = "A new notification has been posted!"
    info.shouldBadge = true
    info.soundName = "default"
    
    subscription.notificationInfo = info
    
    CKContainer.default().publicCloudDatabase.save(subscription, completionHandler: { subscription, error in
        if error == nil {
            // Subscription saved successfully
        } else {
            // An error occurred
        }
    })
}

With this code, we first create a CKQuerySubscription object. This subscription object is what tells CloudKit what it should send notifications for. When initialising this subscription, we include the following:

  • The name of the record type to monitor.
  • A predicate which can be used to limit the subscription to particular records of your specified type. In this tutorial, we want to subscribe to all GlobalNotification records so we pass in a predicate which is always true.
  • One or more triggers telling CloudKit when a notification should be sent. In this example, we only want a notification when a new record is created. Other valid triggers include when a record is updated or deleted.

Next we create a CKNotificationInfo object, provide it with some content, and then assign it to the subscription object. The CKNotificationInfo object is how you format the push notification that is delivered to your users. In this example, we are configuring it with the following properties:

  • An alertBody of "A new notification has been posted!"
  • A shouldBadge value of true. This will cause the app icon on the home screen to increment its number for every notification that comes in.
  • A soundName of "default". This will just use the default iOS notification sound for your app. If you want to use a custom sound, then you will need to use the name of your sound file.
  • A desiredKeys array with a single value. For every key you include in this array, CloudKit will load the corresponding value from the record that triggered the notification and include it in the notification’s user information dictionary.

Further down, we assign the notification info to the subscription, which is then saved to the public CloudKit database for your app.

So that you can see the notification while your app is running, add the following method to your AppDelegate class:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .sound])
}

This code uses the UserNotifications framework to show your notification as if your app wasn’t running at all.

Before running your app, you will need to check if your test device is logged into an iCloud account by going to Settings. If not, you will need to do so because the CloudKit APIs require the current user to be logged in.

Build and run your app from Xcode and accept your app’s request to show notifications. Once you have done that, go back to the CloudKit dashboard for your app and click on Subscription Types in the left sidebar. You should see a new subscription for GlobalNotification records with an INSERT trigger:

How to Use Apple's CloudKit for Push Notifications

4. Sending a Notification

Now, all that’s left for us to do is to send a notification! Still in the CloudKit dashboard, click on Default Zone under Public Data in the left sidebar. Click either on the + button or on New Record to create a new GlobalNotification record. Fill in the content with whatever you want and click Save in the bottom right corner.

Once your record has been saved, you should see the notification appear straight away on your test device:

How to Use Apple's CloudKit for Push Notifications

Conclusion

As you’ve seen, you can easily implement push notifications for your iOS app using CloudKit. The setup is very simple, with only a small number of steps, and the provided APIs allow for any push notifications you may need for your apps.

As always, please be sure to leave your comments and feedback in the comments section below. And do check out some of our other iOS courses and tutorials!

  • How to Use Apple's CloudKit for Push Notifications

    What’s New in iOS 10

    With every new version of iOS, Apple introduces a bunch of new features and enhancements to the developer experience. These are especially exciting to the…
  • How to Use Apple's CloudKit for Push Notifications

    Create SiriKit Extensions in iOS 10

    iOS 10 has finally opened up Siri to third-party apps. In this tutorial, I’ll show you how you can leverage Siri’s capabilities and integrate voice…
  • How to Use Apple's CloudKit for Push Notifications

    iOS 10: Notification Service Extensions

    When receiving a notification in an iOS app, you may want to download content in response to it or edit its content before it is shown to the user. In this…
  • How to Use Apple's CloudKit for Push Notifications

    Easy iOS Push Notifications With back4app

    In this tutorial, you will learn how to easily implement push notifications for iOS apps using back4app as a back-end service. This tutorial covers the…