iOS Local Notification - Callback when in Background

OneGuyInDc picture OneGuyInDc · Dec 9, 2016 · Viewed 8.3k times · Source

Context: My iOS App uses local notifications I schedule local notifications and then I get a call back via didRecieveLocalNotifications when the notifications fire.

This works fine when the app is in foreground however when the App goes in the background I get the iOS notification but no call back.

My Question: How can I get a callback from iOS when the app is in background.

Here is the call back code -

- (void)application:(UIApplication *)application didReceiveLocalNotification:    (UILocalNotification *)notification
{

    //call your method that you want to do something in your app
    NSLog (@"Received Notification");
    [UIApplication sharedApplication].applicationIconBadgeNumber = 1;
    [myRootController HandleLocalNotifications:notification];

}

Answer

matt picture matt · Dec 9, 2016

You are describing application:didReceiveLocalNotification:. This is deprecated in iOS 10. You should be updating to the UserNotification framework.

Now then.

If you app is frontmost, the user gets no alert. Instead, you get application:didReceiveLocalNotification:.

If your app is not frontmost, the user gets an alert. Therefore, you do not get application:didReceiveLocalNotification: because the notification fired. But you do get it if the user received the notification and summoned your app by tapping the notification alert. If the user does that, you will get application:didReceiveLocalNotification: even in the background.

If your app was terminated in the background, however, you will get application:didFinishLaunchingWithOptions: (and you can check the options to learn that you're being launched because of the notification).

If your app was in the background or not running, and the user does not tap the notification and summon your app, you will get nothing at all and will have no way to know that the notification fired. This is because notifications are not for your benefit but are a way of sending a message to the user. (It sounds, from your question, as if you may be misusing local notifications as a way of sending a message to yourself. That is not what they are for.)