新通知到达时,UNNotificationContentExtension不会更新其默认内容页脚

时间:2019-01-28 10:56:36

标签: ios usernotifications usernotificationsui

我有一个通知内容扩展的实现,该扩展在打开时使用iOS提供的默认通知内容(底部的两个文本行):

UNNotificationContentExtension with default content enabled

问题在于,当打开UNNotificationContentExtension新通知到达时,页脚的标题和正文字符串不会更新。我检查了方法didReceive()是否再次被正确调用,并且传递的UNNotification具有正确的更新信息(参数notification.request.content.bodynotification.request.content.title)。但是,操作系统似乎只是忽略了它们,即使我们可以毫无问题地更新内容本身,底部的文本也保持不变。

是否可以强制更新默认内容?似乎没有任何可用于执行此操作的参数和/或方法...

在此先感谢您的答复。

编辑:我还应该补充一点,通知是在本地生成的(APN尚未激活)。代码看起来像这样:

UNMutableNotificationContent *notificationContent = [UNMutableNotificationContent new];
notificationContent.categoryIdentifier = @"my.notification.category";
notificationContent.title = @"My notification title";
notificationContent.body = @"My notification body";

UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:notificationUUID
                                                                      content:notificationContent
                                                                      trigger:notificationTrigger];

UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
[notificationCenter addNotificationRequest:request withCompletionHandler:nil];

1 个答案:

答案 0 :(得分:0)

您需要实现与 UNNotificationContentExtension 相同的 UNNotificationServiceExtension 扩展名。然后,在didReceive方法中,您可以访问有效负载并进行更新。

didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent)将在通知内容扩展的方法之前被调用。

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)

        if let bestAttemptContent = bestAttemptContent {
            // Modify the notification content here...
            bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"

            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)
        }
    }

}