代码之家  ›  专栏  ›  技术社区  ›  Manuel

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

  •  2
  • Manuel  · 技术社区  · 7 年前

    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

    removeAllDeliveredNotifications() 运行并删除所有通知。

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

    0 回复  |  直到 7 年前
        1
  •  5
  •   Simon Bocanegra Thiel    6 年前

    我试过这个建议 @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在 内容处理程序 notificationCenter

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

    dispatch_async(dispatch_get_main_queue(), ^{
        contentHandler(content);
    });
    
    推荐文章