How do I use CKSubscription in an iOS 10 messages extension?

546 views Asked by At

iOS 10 introduced messages extensions, which are the first (to my knowledge) extension which does not require a host application. I am trying to use CloudKit in a messages extension which does not have a host app.

From what I can tell, CKSubscription relies on push notifications. However, I cannot register for push notifications in the usual way (via UIApplication) in app extensions:

let app = UIApplication.shared // Error: not available here blah blah blah

This means it is seemingly impossible to receive CKSubscription notifications in a messages app. I did find hope in the new UserNotifications.framework, but it does not provide any mechanisms for registering for remote notifications. I tried:

override func willBecomeActive(with conversation: MSConversation) {

    // ...

    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.badge, .alert]) { success, error in
        if error != nil { fatalError() }
    }
    center.delegate = self

    // ...
}

// MARK: UNUserNotificationCenterDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
    fatalError() // This never gets called :(
}

But when I update records that are the subject of my CKSubscription, no notification is presented to the user and the delegate is not notified.

Here's my CKSubscription code:

let sub = CKRecordZoneSubscription(zoneID: legitimateZone)

let notifInfo = CKNotificationInfo()
notifInfo.alertBody = "Wow it works! Amazing!"
sub.notificationInfo = notifInfo

privateDB.save(sub) { sub, error in
    if let e = error {
        fatalError("Error saving zone sub: \(e)")
    }
    print("Saved subscription")
}

How do I get CKSubscription notifications in a messages extension?


I don't even need the notification presented to the user, nor do I need to receive them in the background. All I want is to know when records are updated while my extension is running.

If there is another way to do this other than CKSubscription I'd love to hear as well (as long as it's not going to poll CloudKit constantly, wasting my precious 40 requests/sec).

I have tried on both a physical device and in the simulator.

0

There are 0 answers