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

╄→гoц情女王★ 提交于 2019-12-05 19:00:54

Ok looks like after awhile I found one of the ways - its DispatchGroup Its done also in async way with userInteractive quality:

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)")
            }
        }
    }        
}

And that deleted notifications does not exist in getPendingNotificationRequests

You don't have to do all that complex logic as you posted in your answer. You can simply call removeAllPendingNotificationRequests and wait for when it's done within getPendingNotificationRequests method. You can run this code below and see what happens. You will see that after remove will be printed immediately then numbers from 1..63 and then 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)
    }

The reason why it works so is that because all them are tasks put into the queue and run one by one. So, first, it puts 63 notifications, then it removes them, and finally, it counts them. All those tasks go strictly one after each other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!