cancelAllLocalNotifications not working in iOS10

technerd picture technerd · Nov 3, 2016 · Viewed 8.2k times · Source

I want to remove all previous local notification from NotificationCenter when adding new notifications. But it is working in iOS9.0 and lower version but in iOS 10 it fires multiple local notifications. So it seems like cancelAllLocalNotifications not clearing notifications.

Code compile successfully in iOS10.

UIApplication.shared.cancelAllLocalNotifications()

Answer

Wolverine picture Wolverine · Nov 3, 2016

For iOS 10, Swift 3.0

cancelAllLocalNotifications deprecated from iOS 10.

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

You will have to add this import statement,

import UserNotifications

Get notification center. And perform the operation like below

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.

If you want to remove single or multiple specific notification, you can achieve it by below method.

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

Hope it helps..!!