Eri*_*wig 15 cocoa-touch ios unusernotificationcenter
iOS文档说UNUserNotificationCenter'removeAllPendingNotificationRequests()是异步的.
我想要做的是:
打电话removeAllPendingNotificationRequests()去除我所有预定的通知
安排一堆新通知,其中一些可能会或可能不会具有与之前相同的ID
但是由于文档说该方法是在另一个线程上异步运行(并且没有完成回调参数),我担心有时候,根据线程的变化和时间等因素,第1步仍将是我正在创建第2步中的内容,因此它也会杀死我正在制作的一些新通知.
这种东西手动测试有点棘手,因为它取决于时间.所以我很好奇有人知道这是否是我应该担心的事情......
小智 9
在添加通知的文档中,我发现了这一点:
调用 -addNotificationRequest: 将替换具有相同标识符的现有通知请求。
也许解决方案是这样的:
let center = UNUserNotificationCenter.current()
// Create new requests
let newRequests: [UNNotificationRequest] = [...]
let identifiersForNew: [String] = newRequests.map { $0.identifier }
center.getPendingNotificationRequests { pendingRequests in
// Get all pending notification requests and filter only the ones that will not be replaced
let toDelete = pendingRequests.filter { !identifiersForNew.contains($0.identifier) }
let identifiersToDelete = toDelete.map { $0.identifier }
// Delete notifications that will not be replaced
center.removePendingNotificationRequests(withIdentifiers: identifiersToDelete)
// Add all new requests
for request in newRequests {
center.add(request, withCompletionHandler: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
328 次 |
| 最近记录: |