cancelAllLocalNotifications在iOS10中不起作用

tec*_*erd 11 ios uilocalnotification swift ios10

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

代码在iOS10中成功编译.

UIApplication.shared.cancelAllLocalNotifications()
Run Code Online (Sandbox Code Playgroud)

Wol*_*ine 28

对于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()
Run Code Online (Sandbox Code Playgroud)

你必须添加这个import语句,

import UserNotifications
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

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

center.removeDeliveredNotifications(withIdentifiers: ["your notification identifier"])
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你..!!


Mar*_*tos 12

对于iOS 10,目标C:

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center removeAllDeliveredNotifications];
[center removeAllPendingNotificationRequests];
Run Code Online (Sandbox Code Playgroud)

斯威夫特4:

UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
Run Code Online (Sandbox Code Playgroud)

如果要列出所有通知:

func listPendingNotifications() {

    let notifCenter = UNUserNotificationCenter.current()
    notifCenter.getPendingNotificationRequests(completionHandler: { requests in
        for request in requests {
            print(request)
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您收到以下错误[UNUserNotificationCenter'; 你的意思是'NSNotificationCenter'吗?],请在源文件中导入UserNotifications,如下所示:#import <UserNotifications/UserNotifications.h> (2认同)