ios - 为什么没有使用 removeDeliveredNotifications 删除通知?

标签 ios unusernotificationcenter unusernotification unnotificationserviceextension

直到最近(我相信在 iOS 12 发布之前),使用 removeDeliveredNotifications 从通知中心删除远程推送通知按预期工作。

突然间,通知服务扩展中没有任何代码更改,通知不再被删除。

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

    self.contentHandler = contentHandler
    self.content = request.content.mutableCopy() as? UNMutableNotificationContent

    guard let content = content else {
        contentHandler(request.content)
        return
    }

    UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
        let matchingNotifications = notifications.filter({ $0.request.content.threadIdentifier == "myThread" && $0.request.content.categoryIdentifier == "myCategory" })
        UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: matchingNotifications.map({ $0.request.identifier }))
        contentHandler(content)
    }
}

该功能只是在没有删除通知的情况下完成。在真实设备上调试时,它显示 matchingNotifications 包含通知,并且正确提供了要删除的通知 ID。

为了测试,调用 removeAllDeliveredNotifications() 会起作用并删除所有通知。

上面的函数在 override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void)

中调用

这里有什么问题?

最佳答案

我尝试了 @Kymer 的建议并验证在等待一段时间(例如 3 秒)后调用 contentHandler 解决了我的问题,例如

// UNUserNotificationCenter *notificationCenter
// NSArray(NSString *) *matchingIdentifiers;
// UNNotificationContent *content;
if (matchingIdentifiers.count > 0) {
    NSLog(@"NotificationService: Matching notification identifiers to remove: %@.", matchingIdentifiers);               
    [notificationCenter removeDeliveredNotificationsWithIdentifiers:matchingIdentifiers];

    // Note: dispatch delay is in nanoseconds... :(
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3000000000), dispatch_get_main_queue(), ^{
        NSLog(@"Replacing content after 3 seconds.");
        self.contentHandler(content);
    });
}

所以我认为这意味着这是一个时间问题,iOS 在 contentHandler 被调用后积极地卡住进程,并删除 notificationCenter 中所有待处理的删除请求。 p>

编辑: 虽然问题不是关于如何处理它,但评论部分带来了对任意时间延迟的担忧。在我的测试中,在另一个循环上发布回调就足够了,例如

dispatch_async(dispatch_get_main_queue(), ^{
    contentHandler(content);
});

关于ios - 为什么没有使用 removeDeliveredNotifications 删除通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53697279/

相关文章:

c# - iOS 从本地通知打开页面

ios - 等待异步代码完成 Swift

Ios 用户通知内容附件(图片)调整大小/隐藏通知扩展(长按)

ios - 当应用程序在前台时,如何使远程通知出现在通知中心?

ios - 可操作的通知不显示操作 Swift 4

ios - 在 SDK 中实现自定义取消按钮

ios - watch 模拟器按钮似乎已禁用

objective-c - 尝试制作 sqlite 的可写副本时出现错误

iphone - 如何在 appdelegate 中获取指向 viewcontroller 对象的指针