ios - 为什么不使用 removeDeliveredNotifications 删除通知?
问题描述
直到最近(我相信在 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的建议,并验证contentHandler
等待一段时间(例如 3 秒)后调用解决了我的问题,例如
// 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);
});
推荐阅读
- python - nginx从url重定向到django管理面板中的另一个
- javascript - AngularJs MemoryLeak Jquery
- css - 如何使用css获取项目的当前字体大小
- c - 超时从串行读取可变长度数据
- python - 如何从将在列和行之间插值的 Python 表中获取值?
- python - 在 Python 3 中加入列表,如 SQL JOIN
- c++ - 多线程应用程序中的独立日志记录
- wordpress - 是否可以将帖子从一个 WP 站点自动插入到另一个站点?
- linux - 从 UWP 到 Linux/Python 服务器的实时流式传输
- mysql - 在其中一列中具有多个空值的复合唯一键约束