我想在添加新通知时从NotificationCenter中删除所有以前的本地通知。但它适用于iOS9.0及更低版本,但在iOS 10中它会触发多个本地通知。所以似乎cancelAllLocalNotifications
没有清除通知。
在iOS10中成功编译代码。
UIApplication.shared.cancelAllLocalNotifications()
答案 0 :(得分:28)
对于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"])
希望它有所帮助.. !!
答案 1 :(得分:10)
对于iOS 10,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)
}
})
}
答案 2 :(得分:0)
对于iOS 10,您可以使用这种方式删除所有本地通知。 我刚刚测试过,它正在工作。
NSArray *arrayOfLocalNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications] ;
for (UILocalNotification *localNotification in arrayOfLocalNotifications) {
[[UIApplication sharedApplication] cancelLocalNotification:localNotification] ;
}