如何在 iOS 10 通知中获取应用程序状态?

How to get Application states in iOS 10 notification?

我正在使用

userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler

为了在 iOS 10 中获取通知响应,谁能告诉我如何获取其中的应用程序状态?

因为在 iOS 9 之前我用过

application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

在这个方法中,我们可以通过

获取应用状态
application.applicationState

感谢您的帮助。

像这样:

NSString * state = @"Unknown";
UIApplication *application = [UIApplication sharedApplication];
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.
    state = @"UIApplicationStateInactive";
}

if(application.applicationState == UIApplicationStateActive ) {
    //The application received a notification in the active state, so you can display an alert view or do something appropriate.
    state = @"UIApplicationStateActive";
}

if(application.applicationState == UIApplicationStateBackground ) {
    state = @"UIApplicationStateBackground";
}

您可以从项目中的任何位置获取应用程序的状态,例如,

   UIApplication *applicaiton = [UIApplication sharedApplication];

if (applicaiton.applicationState  == UIApplicationStateBackground) {

    NSLog(@"background state");
}

就像您可以使用 UIApplicationStateActive,UIApplicationStateInactive etc 获取相应的状态一样

我做了一些搜索,得到了这些方法

 - (void)userNotificationCenter:(UNUserNotificationCenter *)center  
willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{  
NSLog( @"for handling push in foreground" );  
// Your code
NSLog(@"%@", notification.request.content.userInfo); //for getting response payload data
}  

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response  withCompletionHandler:(void (^)())completionHandler   {  
NSLog( @"for handling push in background" );  
// Your code
NSLog(@"%@", notification.request.content.userInfo); //for getting response payload data 
}