How do I tell if my iPhone app is running when a Push Notification is received?

Viewed 20106

I am sending Push Notifications to my iPhone app, and I'd like a different set of instructions to execute depending on whether the app is already launched or not. I'm new to iPhone development, and while I suspect UIApplication or my project's AppDelegate class has the solution, I haven't found a good answer. Is there an easy way to check for this?

5 Answers

The UIApplication delegate has the method

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

which you need to implement. This receives the notification when the app is running.

If your app is not currently running and a notification is received then your app can be launched with

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

with the notification details held in the launchOptions dictionary. if the dictionary is nil then the user tapped the application icon as normal.

The Apple documentation for push notifications explains this:

However, there are two situations where applicationDidFinishLaunching: is not a suitable implementation site:

  • The application is running when the notification arrives.
  • The notification payload contains custom data that the application can use.

In the first case, where the application is running when iPhone OS receives a remote notification, you should implement the application:didReceiveRemoteNotification: method of UIApplicationDelegate if you want to download the data immediately. After downloading, be sure to remove the badge from the application icon. (If your application frequently checks with its provider for new data, implementing this method might not be necessary.)

This means that if your application:didReceiveRemoteNotification: delegate method is called, your app is running.

Related