如何在iOS 10消息扩展中使用CKSubscription?

时间:2016-08-05 21:51:50

标签: ios swift cloudkit ios10 ios-messages-extension

iOS 10引入了消息扩展,这是第一个(据我所知)扩展,不需要主机应用程序。我正在尝试在没有主机应用程序的邮件扩展中使用CloudKit。

据我所知,CKSubscription依赖于推送通知。但是,我无法在应用扩展程序中以常规方式(通过UIApplication)注册推送通知:

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

这意味着在消息应用中似乎无法接收CKSubscription通知。我确实在新UserNotifications.framework中找到了希望,但它没有提供任何注册远程通知的机制。我试过了:

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 :(
}

但是当我更新作为CKSubscription主题的记录时,不会向用户显示通知,也不会通知代理。

这是我的CKSubscription代码:

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")
}

如何在邮件扩展程序中收到CKSubscription通知?

<小时/> 我甚至不需要向用户提供通知,也不需要在后台接收通知。我想要的只是知道在我的扩展程序运行时何时更新记录。

除了CKSubscription之外还有另一种方法可以做到这一点我也喜欢听(只要它不会不断轮询CloudKit,浪费我宝贵的40个请求/秒)。

我已尝试过物理设备和模拟器。

0 个答案:

没有答案