我怎么知道UNUserNotificationCenter的removeAllPendingNotificationRequests()何时完成?

时间:2017-07-23 18:40:35

标签: ios cocoa-touch unusernotificationcenter

iOS文档说UNUserNotificationCenter的`removeAllPendingNotificationRequests()是异步的。

我想做的是:

  1. 致电removeAllPendingNotificationRequests()以取消我的所有预定通知

  2. 安排一堆新通知,其中一些可能会或可能不会具有与之前相同的ID

  3. 但是由于文档说该方法是在另一个线程上异步运行(并且没有完成回调参数),我担心有时候,根据线程的变化和时间等因素,步骤#1仍然会因为我正在创建第2步中的内容,因此它也会杀死我正在制作的一些新通知。

    这种东西手动测试有点棘手,因为它取决于时间。所以我很好奇有人知道这是否是我应该担心的事情......

2 个答案:

答案 0 :(得分:2)

在添加通知的文档中,我发现了这一点:

  

调用-addNotificationRequest:将替换现有的通知   请求具有相同的标识符。

也许解决方案是这样的:

  1. 创建新的通知请求
  2. 获取所有待处理的内容,并仅过滤掉不会被替换的内容
  3. 删除未替换
  4. 添加所有新通知
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)
     }
}

答案 1 :(得分:0)

我和您的情况相同,并且知道我对这段代码没有问题:

 center.getPendingNotificationRequests(completionHandler: { notifications in
            var notificationIds:[String] = []
            for notification in notifications {
                if notification.identifier != "something_taht_I_dont_dismiss"{
                    notificationIds.append(notification.identifier)
                }
            }
            self.center.removePendingNotificationRequests(withIdentifiers: notificationIds)
            createAllNewNotifications()
        })

如果您要仔细检查所有是否删除了待处理的通知,则可以创建简单的递归方法进行检查。

    func removeAllNotificationsSafe() {
        center.removeAllPendingNotificationRequests()
        checkNotificationsAreRemoved()
    }

    func checkNotificationsAreRemoved() {
        center.getPendingNotificationRequests(completionHandler: { notifications in
            if notifications.count > 0 {
                self.checkNotificationsAreRemoved()
            } else {
                self.doWhathverYouWant()
            }
        }
    }

我认为这不是必需的,因为UNUserNotificationCenter的所有操作将彼此同步。

相关问题