当应用程序从后台收到推送通知或在iOS中终止时,无法从NSNotificationCenter收听通知

时间:2016-09-21 13:25:02

标签: ios objective-c push-notification apple-push-notifications nsnotificationcenter

我在iOS 10中实现了推送通知。一切运作良好。

但我需要在APP收到推送通知时触发API(不仅处于活动状态,还处于后台/终止状态)。

为此,我在App收到如下推送通知时使用NSNotificationCenter进行收听通知:

   - (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSDictionary *userInfo = notification.request.content.userInfo;
    NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]);

    NSLog(@"%@", userInfo);

    if( [UIApplication sharedApplication].applicationState == UIApplicationStateInactive )
    {
        NSLog( @"INACTIVE" );
        completionHandler( UNNotificationPresentationOptionAlert );
    }
    else if( [UIApplication sharedApplication].applicationState == UIApplicationStateBackground )
    {
        NSLog( @"BACKGROUND" );
        completionHandler( UNNotificationPresentationOptionAlert );
    }
    else
    {
        NSLog( @"FOREGROUND" );
        completionHandler( UNNotificationPresentationOptionAlert );
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTheTable" object:nil];

}

我正在ViewController.m这样听取此通知

    - (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTable:) name:@"reloadTheTable" object:nil];
}

 - (void)reloadTable:(NSNotification *)notification
{
// Calling API here
}

当应用程序在前台运行时,此功能正常。 但不是在后台和终止状态。

我或其他任何错误是否有任何错误?

1 个答案:

答案 0 :(得分:2)

  

从iOS 10开始,我们必须添加UserNotifications框架和委托

首先,我们需要在appDelegate.h中进行以下操作

#import <UserNotifications/UserNotifications.h>  
@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>

对于FOREGROUND状态

- (void)userNotificationCenter:(UNUserNotificationCenter *)center  
willPresentNotification:(UNNotification *)notification  
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler  
{  
  NSLog( @"Handle push from foreground" );  
  // custom code to handle push while app is in the foreground  
  NSLog(@"%@", notification.request.content.userInfo);
}   

这适用于背景状态

所以在这里你需要添加通知

- (void)userNotificationCenter:(UNUserNotificationCenter *)center  
 didReceiveNotificationResponse:(UNNotificationResponse *)response  
 withCompletionHandler:(void (^)())completionHandler 
{  
  NSLog( @"Handle push from background or closed" );  
 // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background  
  NSLog(@"%@", response.notification.request.content.userInfo);

  //Adding notification here
  [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTheTable" object:nil];
}  

didReciveRemoteNotificationNotCalled in iOS 10