我正在尝试实现UNNotificationServiceExtension,以便可以在显示推送通知之前修改其内容。它工作正常,但我注意到一种情况,即推送通知不通过UNNotificationServiceExtension。
复制步骤:
结果: 推送通知不会通过UNNotificationServiceExtension进行,UNNotificationServiceExtension会修改标题和正文的内容。仅当我在连接wifi /蜂窝网络之前启动主机应用程序时,此过程才能通过。
预期: 推送通知应始终通过UNNotificationServiceExtension。
这是预期的行为吗?不能保证推送通知总是通过UNNotificationServiceExtension吗?
这是我用于实现UNNotificationServiceExtension的代码:
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)
guard let bestAttemptContent = bestAttemptContent else { return }
bestAttemptContent.title = "title has been modified by extension"
bestAttemptContent.body = "body has been modified by extension"
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)
}
}
}
和我的有效载荷:
{
"aps": {
"alert": {
"body": "my body",
"title": "my title"
},
"content-available": 1,
"mutable-content": 1
}
}