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

tec*_*erd 11 push-notification ios ios-extensions ios10

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

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

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

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

mic*_*oon 36

让我一步一步来看.

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;
Run Code Online (Sandbox Code Playgroud)

当在设备上接收推送通知并且在将其呈现给用户之前触发第一功能.您在函数内部的代码有机会修改此函数内的推送通知的内容.

您可以通过修改做到这一点bestAttemptContent这是一个实例扩展的特性UNNotificationContent:并具有性能title,subtitle,body,attachments等.

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

最后,使用contentHandler调度bestAttemptContent:

self.contentHandler(self.bestAttemptContent); 
Run Code Online (Sandbox Code Playgroud)

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

示例代码

- (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);
}
Run Code Online (Sandbox Code Playgroud)

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

有效负载示例

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

    },
  "attachment-url": ""
}
Run Code Online (Sandbox Code Playgroud)

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

  • @Dmitry你不能调用UIApplication,因此无法从扩展程序到达你的应用代表. (2认同)
  • 请注意,如果您使用 firebase 云消息传递,则密钥名为“mutable_content”而不是“mutable-content”(下划线与破折号) (2认同)