Is there a way to know if the application did become active from a local notification?
I know there is a way to test if the application was launched from a local notification alert; but if it just was sitting out there the background, and received a notification?
I need to run different code, when the app has become active:
Is there a way to do it?
I got the clue to the solution for this from @naveed's tip on checking the state of the application when the didReceiveNotification method is called. No need to check variables etc when the app resumes from the background.
On iOS7 and lower you handle the notifications like this:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
if (application.applicationState == UIApplicationStateInactive ) {
//The application received the notification from an inactive state, i.e. the user tapped the "View" button for the alert.
//If the visible view controller in your view controller stack isn't the one you need then show the right one.
}
if(application.applicationState == UIApplicationStateActive ) {
//The application received a notification in the active state, so you can display an alert view or do something appropriate.
}
}
Update for iOS 8: The following methods are now invoked when the app is opened from the background via a notification.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler {
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler {
}
If the notifications are received while the app is in the foreground, use the methods:
- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *) userInfo {
}
- (void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
}
Note that there is no need to check application state unless you want to support older versions of the OS in your app.