等到使用 removePendingNotificationRequests 删除来自 UNUserNotificationCenter 的本地通知 ios 10 swift 3

Wait till local notifications from UNUserNotificationCenter gets deleted using removePendingNotificationRequests ios 10 swift 3

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

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

并来自文档:

This method executes asynchronously, removing the pending notification requests on a secondary thread.

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

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

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

但如果我 运行 删除此代码后 - 它们仍然存在。但过了一段时间后,在代码中它们消失了。当您即将达到 64 条通知的限制时,在添加新通知之前尤其重要

好的,过了一会儿我找到了其中一种方法 - 它 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

中不存在删除的通知

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