【问题标题】:cancelAllLocalNotifications not working in iOS10取消所有本地通知在 iOS 10 中不起作用
【发布时间】:2016-11-03 09:10:41
【问题描述】:

我想在添加新通知时从 NotificationCenter 中删除所有以前的本地通知。但它在 iOS9.0 及更低版本中工作,但在 iOS 10 中它会触发多个本地通知。所以看起来cancelAllLocalNotifications 没有清除通知。

iOS10代码编译成功

UIApplication.shared.cancelAllLocalNotifications()

【问题讨论】:

  • 对于iOS10的通知,你用的是什么?你在使用“UserNotifications”框架吗?
  • 是的,我正在使用UNUserNotifications 框架
  • 有趣,cancelAllLocalNotifications() 在 iOS 10.2 中为我工作。
  • cancelAllLocalNotifications() 为我工作,直到我链接了 iOS 10 的 UserNotification 框架。通过该链接,我可以使用旧 API 发布本地通知,但取消全部停止工作。

标签: ios swift uilocalnotification ios10


【解决方案1】:

对于 iOS 10,Swift 3.0

cancelAllLocalNotifications 从 iOS 10 中弃用。

@available(iOS, introduced: 4.0, deprecated: 10.0, message: "Use UserNotifications Framework's -[UNUserNotificationCenter removeAllPendingNotificationRequests]")
open func cancelAllLocalNotifications()

您必须添加此导入语句,

import UserNotifications

获取通知中心。并执行如下操作

let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications() // To remove all delivered notifications
center.removeAllPendingNotificationRequests() // To remove all pending notifications which are not delivered yet but scheduled.

如果要删除单个或多个特定通知,可以通过以下方法实现。

center.removeDeliveredNotifications(withIdentifiers: ["your notification identifier"])

希望对您有所帮助..!!

【讨论】:

  • 我实现了相同的。谢谢
【解决方案2】:

对于 iOS 10,目标 C

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center removeAllDeliveredNotifications];
[center removeAllPendingNotificationRequests];

Swift 4

UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

如果您想列出所有通知:

func listPendingNotifications() {

    let notifCenter = UNUserNotificationCenter.current()
    notifCenter.getPendingNotificationRequests(completionHandler: { requests in
        for request in requests {
            print(request)
        }
    })
}

【讨论】:

  • 如果您收到以下错误 [UNUserNotificationCenter';您的意思是“NSNotificationCenter”吗?],请在您的源文件中导入 UserNotifications,如下所示:#import
  • @marcelo dos santos 。这将删除为应用程序发送本地通知。如果用户想打开通知? scheduleLocalNotifications 将起作用。请给出在objective-c中打开的例子。
  • @kiran,你应该重新安排你的通知。我有一种方法可以重新安排我的整个活动,因为我的目标是确保我的用户始终获得最新的信息。
【解决方案3】:

对于 iOS 10,您可以使用这种方式删除所有本地通知。 我刚刚测试过,它工作正常。

    NSArray *arrayOfLocalNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications] ;
    for (UILocalNotification *localNotification in arrayOfLocalNotifications) {
        [[UIApplication sharedApplication] cancelLocalNotification:localNotification] ;
    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多