iOS 10不会调用通知服务扩展

我试图实现新的通知服务扩展,但我有一个问题。

在我的NotificationService.swift文件中,我有这样的代码:

class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { // Modify the notification content here... bestAttemptContent.title = "\(bestAttemptContent.title) [modified]" print(bestAttemptContent.body) contentHandler(bestAttemptContent) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } } 

当我得到推送通知时,didReceive(_ request:UNNotificationRequest,withContentHandler contentHandler:@escaping(UNNotificationContent) – > Void)方法从不调用。

也许我误解了这个扩展是如何工作的?

  1. 而不是运行应用程序。 您必须运行服务扩展作为目标。 然后它会询问你有哪个应用程序运行服务扩展,然后select你的应用程序,它会发送通知。

  2. 确保部署目标小于服务扩展中的设备操作系统。

  3. 请确保有效负载应包含“可变内容”:1。

     {"aps" : { "alert" : { "title" : "Introduction To Notification", "subtitle" : "Session 707", "body" : "New Notification Look Amazing" }, "sound" : "default", "category" : "message", "badge" : 1, "mutable-content": 1 }, "attachment-url": "https://api.buienradar.nl/Image/1.0/RadarMapNL" } 
  4. 不要在aps中添加“Content-available”标志,如果需要添加使其成为0.“Content-available”:0,

在服务扩展上检查您的部署目标。

在10.1版本的设备上进行testing时,我的部署目标设置为10.2,直到我改变了扩展才被调用。

另一个问题可能是debugging..为了使其工作您需要连接服务扩展进程。 在Xcode菜单中debugging>附加到进程>扩展名

您的推送通知有效内容应包含“可变内容”:1个键值对 。

远程通知的aps字典包含值设置为1的可变内容密钥。

推送通知有效载荷的例子JSON:

 { "aps":{ "alert": { "body": "My Push Notification", "title" : "Notification title"}, "mutable-content" : 1, "badge":0}, } 

这工作得很好,我得到推送通知如下: 推送通知

另请注意:

您无法修改无声通知或只能播放声音或标记应用程序图标的通知。

您可以尝试使用Pusher或Houston来testing推送通知。

我疯了。 最后我意识到我的Notification Service Extensiondeployment target10.3 (我的手机)。 我改为10.2 ,它完美的作品