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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…