cancelAllLocalNotifications在iOS10中不起作用

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

代码在iOS10中成功编译。

 UIApplication.shared.cancelAllLocalNotifications() 

对于iOS 10,Swift 3.0

取消从iOS 10中弃用的所有cancelAllLocalNotifications

 @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"]) 

希望能帮助到你..!!

对于iOS 10,Objective C:

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

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

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