当App在iOS 10的后台时,推送通知不会被收到

我正在使用FCM(Firebase云消息传递)在iOS中发送推送通知。

当App处于前台状态时,我可以收到通知。 但是当应用程序处于后台状态时,不会收到通知。 每当应用程序将进入前台状态,才会收到通知。

我的代码是:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { // Print message ID. NSDictionary *userInfo = notification.request.content.userInfo; NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]); // Pring full message. 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 ); }} - (void)applicationDidEnterBackground:(UIApplication *)application { } 

当App处于后台状态时:

 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler 

– 根本不叫。

我在App Capabilities中启用了推送通知以及后台模式下的远程通知。 但应用程序仍然没有收到通知。

我提到了一些StackOverflow问题,但无法解决问题。 有什么补充iOS版本10或在我的代码中的任何错误?

对于iOS 10,我们需要调用下面的两个方法。

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); completionHandler(UNNotificationPresentationOptionAlert); } 

对于背景状态

 - (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); completionHandler(); } 

在此之前,我们必须添加UserNotifications框架并导入到AppDelegate.h文件中

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