didReceiveRemoteNotification non appelé, iOS 10

Dans iOS 9.3, la méthode didReceiveRemoteNotification est appelée dans les deux cas suivants.

1) Lorsque la notification push est reçue 2) Lorsque l'user lance l'application en appuyant sur la notification.

Mais sur iOS 10, je remarque que la méthode didReceiveRemoteNotification ne se triggers PAS lorsque l'user lance l'application en appuyant sur la notification. Il est appelé uniquement lorsque la notification est reçue. Par conséquent, je ne peux pas faire d'autres actions après le lancement de l'application à partir de la notification.

Quelle devrait être la solution pour cela? Une idée?

    type converson

    entrez la description de l'image ici

    pour Swift3

    entrez la description de l'image ici

    pour l'échantillon voir ceci

    importer le framework UserNotifications et append le UNUserNotificationCenterDelegate dans 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<CChar>((deviceToken as NSData).bytes) var token = "" for i in 0..<deviceToken.count { //token += Ssortingng(format: "%02.2hhx", arguments: [chars[i]]) token = token + Ssortingng(format: "%02.2hhx", arguments: [deviceToken[i]]) } print("Registration succeeded!") print("Token: ", token) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { print("Registration failed!") } 

    recevoir les notifications en utilisant ces delegates

      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)") } 

    pour plus d'informations, vous pouvez voir dans Apple API Reference


    objective c

    AppDelegate.h a ces lignes:

    Étape 1

     //Add Framework in your project "UserNotifications" #import <UserNotifications/UserNotifications.h> @interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate> 

    Étape 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) 

    Étape 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; } 

    Cela se triggersra à la suite de l'appel de registerForRemoteNotifications:

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

    Ensuite, lorsqu'un user tape une notification, cela triggers:

    Cela se triggersra dans iOS 10 lorsque l'application est au premier plan ou en arrière-plan, mais pas fermée

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

    Ou utiliser

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

    Ensuite, pour iOS 10, ces deux methods:

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

    J'ai eu le même problème. La bannière de notification est apparue, mais -application:didReceiveRemoteNotification:fetchCompletionHandler: méthode n'a pas été appelée. La solution pour moi qui a fonctionné était d'append l'implémentation de - application:didReceiveRemoteNotification: méthode et forward appel à -application:didReceiveRemoteNotification:fetchCompletionHandler: ::

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

    Source

    C'est un bug iOS. Il sera corrigé dans iOS 10.1. Mais attendez la version 10.1 d'Oct au lieu d'implémenter une nouvelle bibliothèque et supprimez-la plus tard.

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

    Swift code :

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

    BTW, ce problème semble être corrigé dans iOS 10.1. J'ai testé mon application sur 10.1, tout fonctionne bien

    Version de travail iOS 11, Swift 4, Xcode 9 . Copiez simplement le code ci-dessous dans 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..<deviceToken.count { token = token + Ssortingng(format: "%02.2hhx", arguments: [deviceToken[i]]) } print("Registration succeeded!") print("Token: ", token) //send tokens to backend server // storeTokens(token) } //get error here func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Registration failed!") } //get Notification Here below ios 10 func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) { // Print notification payload data print("Push notification received: \(data)") } //This is the two delegate method to get the notification in iOS 10.. //First for foreground @available(iOS 10.0, *) 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)") } //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 restore 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:. } }