您不必像在答案中发布的那样执行所有复杂的逻辑。您可以简单地调用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 条通知,然后删除它们,最后对它们进行计数。所有这些任务严格地一个接一个地进行