简体   繁体   中英

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 (ie 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

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.

I would suggest the current workaround if you didn't said , actually the background experience for ios apps running in background is very poor and there is no guarantee applicationWillTerminate to be called , even to stay alive until the scheduling happens , as IOS always cares about app when it's in front and nearly gives up to 5 minutes to the app when it's sent to background to terminate and that will be dramatically less if the user is opening multiple apps at the same time

You can create a background fetch process to schedule it while the app is closed , but this will have more hassles than the current

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM