【发布时间】:2017-02-23 17:36:21
【问题描述】:
Apple 引入新的扩展名"UNNotificationServiceExtension",但如何从推送通知中启动它?
我了解到服务扩展为有效负载提供端到端加密。
设置推送通知的有效负载需要哪个键?
如何识别payload以及如何从推送通知中启动服务扩展?
【问题讨论】:
标签: ios push-notification ios10 ios-extensions
Apple 引入新的扩展名"UNNotificationServiceExtension",但如何从推送通知中启动它?
我了解到服务扩展为有效负载提供端到端加密。
设置推送通知的有效负载需要哪个键?
如何识别payload以及如何从推送通知中启动服务扩展?
【问题讨论】:
标签: ios push-notification ios10 ios-extensions
让我一步一步来。
UNNotificationServiceExtension - 它是什么?
UNNotificationServiceExtension 是一个应用扩展目标,您将其与您的应用捆绑在一起,目的是在将推送通知传递到设备之前修改推送通知,然后再将其呈现给用户。您可以更改标题、副标题、正文,并通过下载或使用捆绑在应用程序中的附件向推送通知添加附件。
如何创建
转到文件->新建->目标->通知服务扩展并填写详细信息
设置推送通知的有效负载需要哪个键?
您需要将mutable-content 标志设置为1 以触发服务扩展。
另外,如果
(编辑:这不适用。您可以设置或取消设置content-available 设置为1,服务扩展将不起作用。所以要么不设置,要么设置为 0。content-available 标志)
如何识别payload以及如何从推送通知中启动服务扩展?
构建扩展,然后构建并运行您的应用。发送将mutable-content 设置为1 的推送通知。
代码
UNNotificationService 公开了两个函数:
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request
withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler;
- (void)serviceExtensionTimeWillExpire;
第一个函数在设备收到推送通知并呈现给用户之前触发。您在函数内部的代码有机会修改此函数内部的推送通知的内容。
您可以通过修改扩展程序的 bestAttemptContent 属性来做到这一点,该属性是 UNNotificationContent 的一个实例,并具有以下属性:title、subtitle、body、attachments 等。
远程通知的原始负载通过函数参数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);
}
上述代码在 PN 有效载荷中将 [修改] 附加到原始标题。
样本负载
{
"aps": {
"alert": {
"title": "Hello",
"body": "body.."
},
"mutable-content":1,
"sound": "default",
"badge": 1,
},
"attachment-url": ""
}
请注意,attachment-url 键是您自己关心的自定义键,iOS 无法识别。
【讨论】:
You need to set the 'mutable-content' flag to 1 to trigger the service extension. Also, if the 'content-available' is set to 1, the service extension will not work.So either don't set it or set it to 0.
content-available 键的看法是正确的。它也适用于此。我已经相应地更新了答案。