简体   繁体   中英

Which method did application invoke when I click the notification item(in notification bar) when app is in background?

I have found from searching in the Internet: After iOS7, even if an app is killed, if a user clicks a notification associated with the app, the app will invoke this method:

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

I am using an Adhoc provisioning profile, and app is in background and was not killed.

My code is below:

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

// JPush
// IOS 7 Support Required
[JPUSHService handleRemoteNotification:userInfo];  // handle the notification 
completionHandler(UIBackgroundFetchResultNewData);

NSLog(@"%@--userinfo", userInfo);
NSLog(@"%ld--applicationState", (long)[UIApplication sharedApplication].applicationState);

When I test, I get nothing in the device log.

Edit -1

My code for registe APNs in application:didFinishLaunchingWithOptions : My iphone os version is 10.2

// 7.push  regist
if (IOS10) {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"succeeded!");
        }else {
            NSLog(@"error:%@", error);
        }
    }];
} else if (IOS8_10){//iOS8-iOS10
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil];
    [application registerUserNotificationSettings:settings];
    [application registerForRemoteNotifications];
} else {//iOS8以下
    [application registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
}

Edit-2

Refer to Chandan's comment, if add content-available = 1 to aps dictionary, we can wake up the app, but how to add the value to the aps use java :

在此处输入图片说明

Code is below:

public static void pushIos(List<String> registrationIds,Map<String,String> map){
    PushPayload payload = PushPayload.newBuilder()
            .setPlatform(Platform.ios())
            .setAudience(Audience.registrationId(registrationIds))
            .setNotification(Notification.newBuilder()
                    .addPlatformNotification(IosNotification.newBuilder()
                            .setAlert(map.get("title"))
                            .incrBadge(1)
                            .setSound("happy.caf")
                            .addExtra("pushId", map.get("pushId"))
                            .addExtra("pushType",map.get("pushType"))
                            .addExtra("title", map.get("title"))
                            .build())
                    .build())
            .setMessage(Message.content("123"))
            .setOptions(Options.newBuilder()
                     .setApnsProduction(true)
                    .build())
            .build();
    try {
        PushResult result = jPushClient.sendPush(payload);
        System.out.println(result);
    }catch(APIConnectionException e){
        e.printStackTrace();
    } catch (APIRequestException e) {
        e.printStackTrace();
    }
}

Application:didReceiveRemoteNotification: will call in the background only when you have added content-available key with value 1 into the notification payload.

You can check content-available when app in foreground .

NSString* contentAvailable = [NSString stringWithFormat:@"%@", [[userInfo valueForKey:@"aps"] valueForKey:@"content-available"]];

For reference:- Receiving Push Notifications while in background

It looks like you are trying to receive remote push notifications. Did you remember to register for remote push notifications? Also, you need to enable push notifications capability.

Basically, there are three steps.

  1. Enable the Push Notifications capability for your app.
  2. Register with APNs in your app's launch-time code.
  3. Implement support for handling incoming remote notifications.

The code you showed is only for step 3.

See Apple reference on push notifications set up

Try these lines of code, i guess they will solve your issue

This is the code to register for remote notification and to handle them UNUserNotificationCenterDelegate add this delegate

if( SYSTEM_VERSION_LESS_THAN( @"10.0" ) )
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound |    UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];

        NSLog( @"registerForPushWithOptions:" );
    }
    else
    {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
         {
             if( !error )
             {
                 [[UIApplication sharedApplication] registerForRemoteNotifications];  // required to get the app to do anything at all about push notifications
                 NSLog( @"Push registration success." );
             }
             else
             {
                 NSLog( @"Push registration FAILED" );
                 NSLog( @"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription );
                 NSLog( @"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );  
             }  
         }];  
    }

if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]){ // Check it's iOS 8 and above
        UIUserNotificationSettings *grantedSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];

        if (grantedSettings.types == UIUserNotificationTypeNone) {
            NSLog(@"No permiossion granted");
        }
        else {
            NSLog(@"Permission Granted");
        }
    }

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

            {

                // iOS 10 will handle notifications through other methods

                NSLog(@"Notification payload is %@", userInfo);

                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;

                }

                  // 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 );

                }

            }





        - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo  

        {  

            [self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result) {  

            }];  

        }



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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM