didReceiveRemoteNotification when in background

Erwin picture Erwin · Feb 20, 2011 · Viewed 70.2k times · Source

These kind of question has been asked a number of times but i have some specific situation going on.

When my application is active and I receive a PUSH message i'm successfully able to parse the custom payloads and such.

However when my application is in the background and the PUSH arrives the user has to click on the 'View/Open' button in order to get the didReceiveRemoteNotification called and the didFinishLaunchingWithOptions is called after that.

I need to have my application decide if they have to prompt the user with an UIAlert when in the background or suppress the push message based on some local settings.

Any help would be appreciated,

Answer

Bogatyr picture Bogatyr · Feb 20, 2011

You app needs to handle all the possible push notification delivery states:

  • Your app was just launched

  • Your app was just brought from background to foreground

  • Your app was already running in the foreground

You do not get to choose at delivery time what presentation method is used to present the push notification, that is encoded in the notification itself (optional alert, badge number, sound). But since you presumably are in control of both the app and the payload of the push notification, you can specify in the payload whether or not there was an alert view and message already presented to the user. Only in the case of the app is already running in the foreground do you know that the user did not just launch your app through an alert or regularly from the home screen.

You can tell whether your app was just brought to the foreground or not in didReceiveRemoteNotification using this bit of code:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateActive )
        // app was already in the foreground
    else
        // app was just brought from background to foreground
    ...
}