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

时间:2018-12-09 22:22:15

标签: ios unusernotificationcenter unusernotification unnotificationserviceextension

直到最近(我相信是在iOS 12之前的版本),使用removeDeliveredNotifications从Notification Center删除远程推送通知仍然可以正常工作。

突然,在Notification Service Extension中没有任何代码更改,通知就不再被删除。

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)

中调用

这是什么问题?

1 个答案:

答案 0 :(得分:2)

我尝试了@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

中所有未决的删除请求