Search code examples
swiftxcodetimerlocalnotificationcancellation

Stop a notification using swift 3


I have a problem which involves stopping a local notification. This stop button is that so if the user starts a timer (a notification pops up once the timer runs out) and then decides they no longer need the timer, they can cancel it. The problem here is that every method I've tried does not stop the notification from going off. This is mostly because the methods are out of date. Below is my code and I was wondering whether anyone had any ideas on how to stop the notification from going off. Any help would be very much appreciated.

//In the view did load section
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("granted")
        } else {
            print("not granted")
        }
    }


//in a seperate function
let center = UNUserNotificationCenter.current()

content.title = "Local notification"
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.init(named: "1.mp3")
content.badge = 1

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: time, repeats: false)
let request = UNNotificationRequest(identifier: "requestAlarm", content: content, trigger: trigger)
center.add(request)

center.delegate = self

Solution

  • Tell the user notification center to removeAllPendingNotificationRequests.