iOS:所有本地通知都消失了,而不是我列出的那些

iOS: all local notifications disappear instead of the ones I list

我的应用程序使用了很多预定的本地通知,并且在某些事件上我重新安排了通知并想清除一些已发送的通知,而不是全部。

粗略的伪代码:

// Clear pending notifications that haven't been delivered yet
notificationCenter.removeAllPendingNotificationRequests()

// Get the delivered notifications (async), filter out the ones that should be removed
// and remove them
notificationCenter.getDeliveredNotifications() { notifications in
  let notificationsToRemove = notifications.filter { some boolean operation }
  let identifiersToRemove = notificationsToRemove.map { [=11=].identifier }
  notificationCenter.removeDeliveredNotificationsWithIdentifiers(identifiersToRemove)
}

// Schedule the next set of notifications
let nextBatchOfNotifications = notificationGenerator.generate()
for notification in nextBatchOfNotifications) {
  notificationCenter.schedule(notification)
}

但是,当我这样做时,绝大多数时间都会导致所有已发送的通知被清除。在极少数情况下,它只会导致我要求删除的部分已发送通知被删除(或者 none)。

至少在我的例子中,与查询和安排通知相关的所有功能的异步性质是问题所在,删除 pending/delivered 通知并尝试安排新通知的事实意味着 iOS 会搞得一团糟,无法正确执行我的要求。

解决方案似乎是等待发送的通知被返回,删除它们,再等一会儿,然后安排新的通知。自从我进行了此更改以来,到目前为止我还没有发现任何问题!

用等待更新的粗略伪代码

// Clear pending notifications that haven't been delivered yet
notificationCenter.removeAllPendingNotificationRequests()

// Get the delivered notifications (async), filter out the ones that should be removed
var identifiersToRemove
var semaphore
notificationCenter.getDeliveredNotifications() { notifications in
  let notificationsToRemove = notifications.filter { some boolean operation }
  identifiersToRemove = notificationsToRemove.map { [=10=].identifier }
  semaphore.signal()
}

semaphore.wait()
notificationCenter.removeDeliveredNotificationsWithIdentifiers(identifiersToRemove)

Thread.sleep(0.1)

// Schedule the next set of notifications
let nextBatchOfNotifications = notificationGenerator.generate()
for notification in nextBatchOfNotifications) {
  notificationCenter.schedule(notification)
}

我不确定是否有更好的方法在请求删除已发送的通知后等待 0.1 秒...没有回调让我知道它已经完成所以这是最好的我现在可以想出!

(如果伪代码难以理解,我深表歉意,我的代码有些遗留,所以仍在 Objective-C 中,我认为在这个时代分享它不是特别合适!)