0

I have an app that needs to be left running in the background in order to execute its background processes. I want to send a notification to the user any time the user closes the app from multitasking so that I can prompt them to reopen the app. I have read the discussion here: Local notification on application termination, and tried those solutions, but none have resulted in a reliable notification upon user termination of the app.

Here is what my code looks like right now, in my AppDelegate.m file:

- (void)applicationWillTerminate:(UIApplication *)application
{
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
    [center removeAllDeliveredNotifications];
    //Try and alert the user
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody = @"App was terminated unexpectedly. Notification-based logging won't work. Tap to restart App!";
    notification.soundName = UILocalNotificationDefaultSoundName;
    [application scheduleLocalNotification:notification];

    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

In the debug mode of the simulator, this solution always delivers a notification when the app is closed from multitasking. Unfortunately, on my phone, I only occasionally get this notification upon termination of the app. Many times I have killed the app from multitasking and no notification appears.

I am re-asking the question because the responses to the linked post are years old, and I have reason to believe this is achievable. Both the Moment and TripLog apps have the exact behavior I want.

If anyone has a reliable solution to send a local notification to the user as soon as they close an app from multitasking, that would be much appreciated. I code in Objective C, so a solution in Objective C would be ideal.

Community
  • 1
  • 1
Carielle
  • 11
  • 6
  • "Many times I have killed the app from multitasking and no notification appears" Perhaps you don't get a notification because the app was already terminated in the background by the system and so is no longer running and there is no `applicationWillTerminate` event. There is _no_ way to detect this. Indeed, that is exactly what http://stackoverflow.com/a/17988326/341994 says. – matt Mar 02 '17 at 00:38

1 Answers1

0

There is no way to make sure your app keeps running in the background. The runtime is allowed to terminate it silently in the background at any time, and you cannot get an event when that happens.

The apps that seem to do this successfully are probably actually doing something in the background, that is, for example, they are doing core location updates or playing a sound. That sort of specialized behavior greatly increases the chances of getting an applicationWillTerminate in the background.

matt
  • 515,959
  • 87
  • 875
  • 1,141