8

I would like to know if there is a way to know if an app (which can be closed or open in background) has been launched with a click on:

  • a notification (in the notification center) ?
  • or the app icon on the springboard ?

Thanks !!

Cfr
  • 5,092
  • 1
  • 33
  • 50
toto_tata
  • 14,526
  • 27
  • 108
  • 198

2 Answers2

11

put this code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UILocalNotification *notification = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];

    if (notification) {
        // launched from notification
    } else {
        // from the springboard
    }
}

in your UIApplicationDelegate.

Cfr
  • 5,092
  • 1
  • 33
  • 50
  • Thanks, works perfectly ! Nota for other developers: the method - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions fully replaces the standard method - (BOOL)application:(UIApplication *)application didFinishLaunching which doesn't work anymore when the didFinishLaunchingWithOptions method is added. – toto_tata Oct 17 '12 at 17:57
  • What's the current way to do this? UserNotificationsWillAppear doesn't have launchOptions –  Jan 10 '19 at 09:32
  • Daniel, what is "UserNotificationsWillAppear"? 3d-party library method? – Cfr Jan 24 '19 at 11:35
  • Do you have a newer example of this? ios13+ ish? – Jalil May 24 '21 at 18:33
6

From Apple Docs on Scheduling, Registering, and Handling Notifications :

iOS Note: In iOS, you can determine whether an application is launched as a result of the user tapping the action button or whether the notification was delivered to the already-running application by examining the application state. In the delegate’s implementation of the application:didReceiveRemoteNotification: or application:didReceiveLocalNotification: method, get the value of the applicationState property and evaluate it. If the value is UIApplicationStateInactive, the user tapped the action button; if the value is UIApplicationStateActive, the application was frontmost when it received the notification.

Black Frog
  • 11,595
  • 1
  • 35
  • 66
  • except this doesn't handle the case where the application is launched with pre-existing notifications (or notifications received when the device was asleep), then the application is launched or brought to the foreground by the user, and then the user pulls down the notification center from the top of the screen and clicks on that pre-existing notification. At the time the event is processed, the app will be in the foreground, even though the user clicked on the notification and would expect some application-specific behaviour. – Allan Nienhuis Nov 24 '17 at 18:34