didReceiveRemoteNotification no llamado, iOS 10

En iOS 9.3, se didReceiveRemoteNotification método didReceiveRemoteNotification en las dos ocasiones siguientes.

1) Cuando se recibe la notificación de inserción 2) Cuando el usuario inicia la aplicación tocando en la notificación.

Pero en iOS 10, noto que el método didReceiveRemoteNotification NO se didReceiveRemoteNotification cuando el usuario inicia la aplicación tocando en la notificación. Se llama solo cuando se recibe la notificación. Por lo tanto, no puedo hacer nada más después de que la aplicación se inicia desde la notificación.

¿Cuál debería ser la solución para esto? ¿Alguna idea?

tipo converson

enter image description here

para Swift3

enter image description here

para la muestra, vea esto

importar el marco de UserNotifications y agregar el UNUserNotificationCenterDelegate en Appdelegate

 import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //create the notificationCenter let center = UNUserNotificationCenter.current() center.delegate = self // set the type as sound or badge center.requestAuthorization(options: [.sound,.alert,.badge]) { (granted, error) in // Enable or disable features based on authorization } application.registerForRemoteNotifications() return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // let chars = UnsafePointer((deviceToken as NSData).bytes) var token = "" for i in 0.. 

recibir las notificaciones usando este delegado

  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) { print("Handle push from foreground") // custom code to handle push while app is in the foreground print("\(notification.request.content.userInfo)") } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("Handle push from background or closed") // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background print("\(response.notification.request.content.userInfo)") } 

para obtener más información, puede ver en Apple API Reference


C objective

AppDelegate.h tiene estas líneas:

Paso 1

 //Add Framework in your project "UserNotifications" #import  @interface AppDelegate : UIResponder  

Paso 2

AppDelegate.m

  // define macro #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) #define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending) 

Paso 3

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { application.applicationIconBadgeNumber = 0; if( SYSTEM_VERSION_LESS_THAN( @"10.0" ) ) { [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]]; [[UIApplication sharedApplication] registerForRemoteNotifications]; //if( option != nil ) //{ // NSLog( @"registerForPushWithOptions:" ); //} } else { UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) { if( !error ) { // required to get the app to do anything at all about push notifications [[UIApplication sharedApplication] registerForRemoteNotifications]; NSLog( @"Push registration success." ); } else { NSLog( @"Push registration FAILED" ); NSLog( @"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription ); NSLog( @"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion ); } }]; } return YES; } 

Se disparará como resultado de llamar a registerForRemoteNotifications:

  - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { // custom stuff we do to register the device with our AWS middleman } 

Luego, cuando un usuario toca una notificación, esto activa:

Se activará en iOS 10 cuando la aplicación esté en primer plano o en segundo plano, pero no cerrada

  -(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { // iOS 10 will handle notifications through other methods if( SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO( @"10.0" ) ) { NSLog( @"iOS version >= 10. Let NotificationCenter handle this one." ); // set a member variable to tell the new delegate that this is background return; } NSLog( @"HANDLE PUSH, didReceiveRemoteNotification: %@", userInfo ); // custom code to handle notification content if( [UIApplication sharedApplication].applicationState == UIApplicationStateInactive ) { NSLog( @"INACTIVE" ); completionHandler( UIBackgroundFetchResultNewData ); } else if( [UIApplication sharedApplication].applicationState == UIApplicationStateBackground ) { NSLog( @"BACKGROUND" ); completionHandler( UIBackgroundFetchResultNewData ); } else { NSLog( @"FOREGROUND" ); completionHandler( UIBackgroundFetchResultNewData ); } } 

o usar

  - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { [self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result) { }]; } 

Luego, para iOS 10, estos dos métodos:

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

Yo tuve el mismo problema. Apareció el banner de notificación, pero -application:didReceiveRemoteNotification:fetchCompletionHandler: método no se -application:didReceiveRemoteNotification:fetchCompletionHandler: . La solución para mí que funcionó fue agregar la implementación de - application:didReceiveRemoteNotification: method y reenviar call a -application:didReceiveRemoteNotification:fetchCompletionHandler: :

 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { [self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result){}]; } 

Fuente

Es un error de iOS. Se solucionará en iOS 10.1. Pero solo espere la versión 10.1 en octubre en lugar de implementar una nueva biblioteca y eliminarla más tarde.

https://forums.developer.apple.com/thread/54322

Código Swift :

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.currentNotificationCenter() center.delegate = self } // ... return true } @available(iOS 10.0, *) public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print(response.notification.request.content.userInfo) } @available(iOS 10.0, *) public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { print(notification.request.content.userInfo) } 

Por cierto, este problema parece estar solucionado en iOS 10.1. Probé mi aplicación en 10.1, todo funciona bien

Versión de trabajo iOS 11, Swift 4, Xcode 9 . Solo copie y pegue el siguiente código en AppDelegate.

 import UIKit import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if #available(iOS 10, *) { // iOS 10 support //create the notificationCenter let center = UNUserNotificationCenter.current() center.delegate = self // set the type as sound or badge center.requestAuthorization(options: [.sound,.alert,.badge]) { (granted, error) in if granted { print("Notification Enable Successfully") }else{ print("Some Error Occure") } } application.registerForRemoteNotifications() } else if #available(iOS 9, *) { // iOS 9 support UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) UIApplication.shared.registerForRemoteNotifications() } else if #available(iOS 8, *) { // iOS 8 support UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) UIApplication.shared.registerForRemoteNotifications() } else { // iOS 7 support application.registerForRemoteNotifications(matching: [.badge, .sound, .alert]) } return true } //get device token here func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { var token = "" for i in 0.. Void) { print("Handle push from foreground") // custom code to handle push while app is in the foreground print("\(notification.request.content.userInfo)") } //Second for background and close @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response:UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("Handle push from background or closed") // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background print("\(response.notification.request.content.userInfo)") } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restre your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } 

swift 4, si está utilizando la versión de ios 11 o xcode mayor que 9.0, entonces debe tener el método de delegado UNUserNotification para llamar a la notificación didReceiveRemoteNotification

  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { //Your code to handle events }