[英]When should Notifications in the NSUserNotificationCenter be removed?
[英]Why are notifications not removed with removeDeliveredNotifications?
直到最近(我相信在iOS 12发布之前),从通知中心删除远程推送通知使用removeDeliveredNotifications
按预期工作。
突然,在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)
调用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
删除任何待处理的删除请求
编辑:虽然问题不是关于如何处理它,但评论部分引起了对任意时间延迟的担忧。 在我的测试中,在另一个循环上发布回调就足够了,例如
dispatch_async(dispatch_get_main_queue(), ^{
contentHandler(content);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.