【问题标题】:iOS: all local notifications disappear instead of the ones I listiOS:所有本地通知都消失了,而不是我列出的通知
【发布时间】:2022-01-17 06:37:58
【问题描述】:

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

粗略的伪代码:

// 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 { $0.identifier }
  notificationCenter.removeDeliveredNotificationsWithIdentifiers(identifiersToRemove)
}

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

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

【问题讨论】:

    标签: ios usernotifications


    【解决方案1】:

    至少在我的情况下,与查询和调度通知相关的所有功能的异步性质是问题所在,而删除待处理/传递的通知并尝试安排新通知的事实意味着 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 { $0.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 中,我认为在当今时代不适合分享!)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-25
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多