Search code examples
iosswiftnotificationslocalnotificationunusernotificationcenter

Scheduling a local notification when the app is terminated


My goal is to create a local notification that will trigger if the user has not launched the app for 2 weeks. I use a Manager class to handle the scheduling of the app's local notifications.

This is my current solution:

func applicationWillTerminate(_ application: UIApplication) {
    NotificationManager.shared.schedule(notification)
}

However, applicationWillTerminate is not going to be called - and thus the notification will not be scheduled - if the app is terminated while it is in the background (i.e. it is swiped from the dock).

Are there any workarounds to this?

One workaround I thought about was to schedule the notification whenever the app enters the background, and then call removePendingNotificationRequests() if the app becomes active again, as shown below:

func applicationDidEnterBackground(_ application: UIApplication) {
    NotificationManager.shared.schedule(notification)
}

func applicationDidBecomeActive(_ application: UIApplication) {
   UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["notification"])
}

The issue with this is that it seems to me like a wasteful and suboptimal solution. Is there a more elegant solution than scheduling this notification


Solution

  • You are pretty close to the strategy I would use. Rather than schedule the notification when you enter the background, clear and schedule every time the app becomes active.

    func applicationDidBecomeActive(_ application: UIApplication) { 
        UNUserNotificationCenter.current().removePendingNotificationRequests( withIdentifiers: ["notification"]
        NotificationManager.shared.schedule(notification)
    }
    

    Every time you launch, you should setup a notification for 2 weeks in the future. If they launch tomorrow, delete the old notification, and setup a new one for two week after that.