Search code examples
iosswift3uilocalnotificationuiswitch

Using a switch to enable and disable local notifications (swift 3)


I'm making my first app, and one of the features is a to-do list. I have a switch that disables local notifications when it's off, and when it's on it's supposed to enable them for as long as the switch is on. I save the switch state using UserDefaults, the notifications do appear, however, they don't repeat even though I specify that they should. Right now I have the notifications set up to repeat every 60 seconds for testing but when it works it will be two days. How can I make the notifications repeat as long as the switch is on? My code for the switch:

@IBOutlet weak var switchout: UISwitch!

@IBAction func notifswitch(_ sender: Any) {
print ("hello")
    if switchout.isOn
    {
        if #available(iOS 10.0, *), list.isEmpty == false {

            let content = UNMutableNotificationContent()
            content.title = "You have tasks to complete!"
            content.subtitle = ""
            content.body = "Open the task manager to see which tasks 
need completion"
            let alarmTime = Date().addingTimeInterval(60) 
            let components = Calendar.current.dateComponents([.weekday, 
.hour, .minute], from: alarmTime)
            let trigger = UNCalendarNotificationTrigger(dateMatching: 
components, repeats: true)
            let request = UNNotificationRequest(identifier: 
"taskreminder", content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request, 
withCompletionHandler: nil)
        } else {
            print ("hello")
        }

    } else
    {
        UIApplication.shared.cancelAllLocalNotifications()
    }

    self.saveSwitchesStates()

Solution

  • I suspect you're using the wrong cancel API.

    Instead of:

    UIApplication.shared.cancelAllLocalNotifications()
    

    Try using:

    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    

    That cancels everything for your app though. If you want to do specific notifications, you can do:

    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: "taskreminder")
    

    More info can be seen at this closely related question.

    2 )

    Now in regards to your notifications not repeating, even though you've set true when setting up the trigger, I see that the time you're setting up requires a match for [.weekday, .hour, .minute], which means it'll repeat every day of the week at the same time.

    Try passing THIS to UNNotificationRequest instead:

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)