如何在iOS10中使用UNNotification的通知服务扩展

Apple引入了新的扩展名“UNNotificationServiceExtension” ,但如何从推送通知中启动它?

我读到服务扩展为有效负载提供端到端加密。

设置推送通知的有效负载需要哪个密钥?

如何识别有效负载以及如何从推送通知启动服务扩展?

让我一步一步来看。

UNNotificationServiceExtension – 它是什么?

UNNotificationServiceExtension是一个App Extenstion目标,它与您的应用程序捆绑在一起,目的是在将推送通知传递给设备之前修改推送通知,然后再将其呈现给用户。 您可以通过下载或使用应用程序中捆绑的附件来更改标题,副标题,正文以及附加推送通知的附件。

如何创造

转到文件 – >新建 – >目标 – >通知服务扩展并填写详细信息

设置推送通知的有效负载需要哪个密钥?

您需要将mutable-content标志设置为1以触​​发服务扩展。 此外,如果content-available设置为1 ,则服务扩展将不起作用。 因此要么不设置它,要么将其设置为0. (编辑:这不适用。您可以设置或取消设置content-available标志)

如何识别有效负载以及如何从推送通知启动服务扩展?

构建扩展,然后构建并运行您的应用程序。 发送推送通知,其中mutable-content设置为1

UNNotificationService公开了两个函数:

 - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler; - (void)serviceExtensionTimeWillExpire; 

当在设备上接收推送通知时以及在将其呈现给用户之前触发第一function。 您在函数内部的代码有机会修改此函数内的推送通知的内容。

您可以通过修改扩展的bestAttemptContent属性来实现此目的,该属性是UNNotificationContent一个实例,并具有属性: titlesubtitlebodyattachments等。

远程通知的原始有效负载通过函数参数request request.content属性传递。

最后,使用contentHandler调度bestAttemptContent:

 self.contentHandler(self.bestAttemptContent); 

在第一种方法中你有足够的时间来做你的东西。 如果时间到期,则会使用您的代码迄今为止所做的最佳尝试调用第二个方法。

示例代码

 - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { self.contentHandler = contentHandler; self.bestAttemptContent = [request.content mutableCopy]; // Modify the notification content here... self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title]; self.contentHandler(self.bestAttemptContent); } 

上面的代码将[modified]附加到PN有效载荷中的原始标题。

有效负载示例

 { "aps": { "alert": { "title": "Hello", "body": "body.." }, "mutable-content":1, "sound": "default", "badge": 1, }, "attachment-url": "" } 

请注意, attachment-url键是您自己关注的自定义键,iOS无法识别。