5

使用来自 的新本地通知UNUserNotificationCenter。我尝试删除带有一些标识符的通知:

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)

并从文档中:

此方法异步执行,删除辅助线程上的未决通知请求。

完成处理程序不存在。那么我怎么知道它什么时候真正被删除呢?在继续之前,我需要确保该标识符不再存在。

我知道我可以使用下一个代码

notificationCenter.getPendingNotificationRequests { (requests) in
        for request in requests {
         }
}

但是,如果我在删除后立即运行此代码 - 它们仍然存在。但是经过一段时间和后来的代码,它们就消失了。当您即将丰富 64 个通知的限制时,在添加新通知之前尤其重要

4

2 回答 2

0

您不必像在答案中发布的那样执行所有复杂的逻辑。您可以简单地调用removeAllPendingNotificationRequests并等待它在getPendingNotificationRequests方法内完成。您可以在下面运行此代码,看看会发生什么。您将看到after remove将立即打印然后从1..63和 开始的数字0

let notificationCenter = UNUserNotificationCenter.current()

    for i in 1 ... 63 {
        let components: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second]

        let date = Calendar.current.date(byAdding: .hour, value: 1, to: Date())!

        let dateComponents = Calendar.current.dateComponents(components, from: date)

        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

        let content = UNMutableNotificationContent()

        content.title = "Title"
        content.body = "Body"
        content.sound = UNNotificationSound.default()

        let request = UNNotificationRequest(identifier: "id" + String(i),
                content: content, trigger: trigger)

        notificationCenter.add(request) {
            (error) in

            print(i)
        }
    }

    notificationCenter.removeAllPendingNotificationRequests()

    print("after remove")

    notificationCenter.getPendingNotificationRequests() {
        requests in
        print(requests.count)
    }

之所以如此,是因为它们都是放入队列并一一运行的任务。因此,它首先放置 63 条通知,然后删除它们,最后对它们进行计数。所有这些任务严格地一个接一个地进行

于 2017-09-26T19:48:44.040 回答
-1

好吧,好像过了一会儿我找到了一种方法——DispatchGroup 它也以异步的方式完成了userInteractive质量:

let dq = DispatchQueue.global(qos: .userInteractive)
dq.async {
    let group  = DispatchGroup()
    group.enter()
    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: arr)
group.leave()

    group.notify(queue: DispatchQueue.main) { () in
        UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in
            for request in requests {
                print("||=> Existing identifier is \(request.identifier)")
            }
        }
    }        
}

并且删除的通知不存在getPendingNotificationRequests

于 2017-06-02T14:44:31.463 回答