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

0

7

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.

Dori answered 5/8, 2016 at 21:51 Comment(3)
Hey! I am struggling basically with the same thing. Do you already have a solution by any chance?Geomancy
@Geomancy No, I'm afraid I don't have a good solution. At this point I'm ensuring all record changes are the result of a message being sent. That way, whenever I receive a message while the extension is running, I know I should go and check for changes.Dori
I did file a bug report for this also (rdar://problem/27731630)Dori

© 2022 - 2024 — McMap. All rights reserved.