Reputation: 15365
I'm trying to fire a local notification after my app gets killed to warn the user that whatever the app was doing, it can't do it anymore. MileIQ does something similar with background location tracking when warning their user that the app got killed and that they need to restart it if they want trips to still be recorded.
My code looks like this in a UIApplicationWillTerminateNotification
handler:
let notification = UILocalNotification()
notification.soundName = UILocalNotificationDefaultSoundName
notification.alertTitle = "title"
notification.alertBody = "body"
notification.fireDate = NSDate().dateByAddingTimeInterval(6)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
The magic fireDate
delay set at 6 seconds is because applicationWillTerminate
has 5 seconds to the app to cleanup, and iOS kills the app if the method doesn't return in time.
What I noticed is that if I fire the local notification instantly, it appears very briefly and gets dismissed when the app gets killed by iOS. By adding a 6 delay, the notification appears about 50% of the time and doesn't get dismissed.
What I'm looking for is a reliable solution to show this local notification after the app gets killed. Any idea how to do this?
Upvotes: 1
Views: 1019
Reputation: 15365
After digging a bit more into this and seeing this comment, I figured out a consistent way to show the local notification following a UIApplicationWillTerminateNotification
event:
presentNotification() // see code in original question
sleep(2)
What I think was happening is that the app would terminate faster than it could show the local notification, so by calling sleep(2)
I made the app shut down a bit slower to allow presenting the notification.
The local notification now shows consistently when a user shuts down the app manually. Not too concerned about iOS killing the app without warning, so this is a good solution for me.
Upvotes: 3
Reputation: 328
aplicationWillTerminate method doesn't ensure to be called at the time of termination . You can read about it in more detail here Local notification on application termination
Upvotes: 0