Apple 引入新的扩展名 "UNNotificationServiceExtension" , 但如何从推送通知启动它?
我读到服务扩展为负载提供端到端加密。
设置推送通知的负载需要哪个键?
如何识别有效负载以及如何从推送通知启动服务扩展?
最佳答案
让我一步一步来。
UNNotificationServiceExtension - 它是什么?
UNNotificationServiceExtension 是一个 App Extension 目标,您将其与您的应用程序捆绑在一起,目的是在将推送通知传递给设备之前修改推送通知,然后再将其呈现给用户。您可以更改标题、副标题、正文,还可以通过下载或使用应用中捆绑的附件向推送通知添加附件。
如何创建
转到文件 -> 新建 -> 目标 -> 通知服务扩展并填写详细信息
设置推送通知的负载需要哪个键?
您需要将mutable-content
标志设置为1
以触发服务扩展。
此外,如果
(编辑:这不适用。您可以设置或取消设置 content-available
设置为 1
,则服务扩展将不起作用。所以要么不设置它,要么设置为 0。content-available
标志)
如何识别有效负载以及如何从推送通知启动服务扩展?
构建扩展,然后构建并运行您的应用。发送 mutable-content
设置为 1
的推送通知。
代码
UNNotificationService 公开了两个函数:
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request
withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler;
- (void)serviceExtensionTimeWillExpire;
第一个函数在设备收到推送通知并呈现给用户之前触发。您在函数内部编写代码有机会修改此函数内部推送通知的内容。
你通过修改你的扩展的 bestAttemptContent
属性来做到这一点,它是 UNNotificationContent
的一个实例并且具有属性:title
, 副标题
、正文
、附件
等
远程通知的原始负载是通过函数参数 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 无法识别。
关于ios - 如何在 iOS 中使用带有 UNNotification 的通知服务扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40040583/