cancelAllLocalNotifications 在 iOS10 中不起作用

cancelAllLocalNotifications not working in iOS10

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

代码在 iOS10.

中编译成功
UIApplication.shared.cancelAllLocalNotifications()

对于iOS10,Swift3.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"])

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

对于iOS10,Objective 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)
        }
    })
}

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

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