Detect if application: didReceiveRemoteNotification: fetchCompletionHandler: was called by tapping on a notification in Notification Center

Devfly picture Devfly · Apr 19, 2014 · Viewed 29.4k times · Source
application: didReceiveRemoteNotification: fetchCompletionHandler:

is different from

application: didReceiveRemoteNotification:

How? from the docs:

Unlike the application:didReceiveRemoteNotification: method, which is called only when your app is running, the system calls this method regardless of the state of your app. If your app is suspended or not running, the system wakes up or launches your app and puts it into the background running state before calling the method. If the user opens your app from the system-displayed alert, the system calls this method again so that you know which notification the user selected.

My struggle is: I want to know if the method was called by the user tapping an a system-displayed alert from the Notification Center or from a silent push notification that wakes up the device. Currently, as far as I can see, there is no obvious way to differentiate.

- (BOOL)application: didFinishLaunchingWithOptions:

Tracking the launchOptions in the above method is not a solution because it's only called if the app is suspended/not running in background. If it's running in the background it doesn't get called.

Answer

race_carr picture race_carr · Apr 19, 2014

The Apple docs are a bit confusing

application: didReceiveRemoteNotification: fetchCompletionHandler:  

is used if your application supports the remote-notification background mode (ie you're doing BackgroundFetch.)

application: didReceiveRemoteNotification:  

is called when the OS receives a RemoteNotification and the app is running (in the background/suspended or in the foreground.)
You can check the UIApplicationState to see if the app was brought to foreground by the user (tapping on notification) or was already running when notification comes in.

- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
      UIApplicationState state = [application applicationState];
        // user tapped notification while app was in background
    if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
         // go to screen relevant to Notification content
    } else {
         // App is in UIApplicationStateActive (running in foreground)
         // perhaps show an UIAlertView
    }
}