1

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:

enter image description here

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();
    }
}
aircraft
  • 25,146
  • 28
  • 91
  • 166
  • This is a bug of Xcode8 + iOS10, NSLog Not Displaying At All. You can check this link http://stackoverflow.com/questions/7856508/nslog-not-printing-to-console – Chandan kumar Jan 12 '17 at 02:55
  • @Chandan , sorry bro, this is not caused by your said bug, and the other NSLog info I can find also. – aircraft Jan 12 '17 at 03:06
  • If i am not wrong we cant debug when we using Adhoc provisioning profile. So how will it Display NSLog. – Chandan kumar Jan 12 '17 at 03:33
  • @Chandan, see my this post : http://stackoverflow.com/questions/41582213/is-it-possible-to-debug-my-app-with-adhoc-provisioning-profile-in-xcode/41582650?noredirect=1#comment70379634_41582650 – aircraft Jan 12 '17 at 03:35
  • application:didReceiveRemoteNotification: will call in the background only when you have added content-available key with value 1 into the notification payload.http://stackoverflow.com/questions/14616261/receiving-push-notifications-while-in-background – Chandan kumar Jan 12 '17 at 06:31
  • @Chandan, thanks, I think this is the reason, but how to get the push notification information? – aircraft Jan 12 '17 at 06:47
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/132963/discussion-between-chandan-and-aircraft). – Chandan kumar Jan 12 '17 at 07:17
  • You can check when app in foreground . NSString* contentAvailable = [NSString stringWithFormat:@"%@", [[userInfo valueForKey:@"aps"] valueForKey:@"content-available"]]; – Chandan kumar Jan 12 '17 at 07:23
  • @Chandan, could i set `content-available` to `1` ? when push ? how to set? – aircraft Jan 12 '17 at 07:27
  • Yes Simply add content-available = '1' in .php file. Example :- "data": { "alert": "Hello World!", content-available = '1' } – Chandan kumar Jan 12 '17 at 08:02
  • Anatomy of a Basic Push Notification : https://www.raywenderlich.com/123862/push-notifications-tutorial – Chandan kumar Jan 12 '17 at 08:05
  • @Chandan, i successed, bro, thank you, please answer my question , I will choose your answer. – aircraft Jan 12 '17 at 08:53

3 Answers3

3

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

Community
  • 1
  • 1
Chandan kumar
  • 1,074
  • 12
  • 31
0

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

auspicious99
  • 3,902
  • 1
  • 44
  • 58
  • off course I did those, so I can recieve the remote notification, then I can click the push notification bar's item, does it ? – aircraft Jan 12 '17 at 03:38
  • Can you show the code for step 2? If there's an error there, that may result in your app not properly receiving the push notification. – auspicious99 Jan 12 '17 at 03:49
0

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);
        }  
Developer
  • 822
  • 9
  • 23
  • thanks your answer, I mean click the notification item re-come in my app, my app did not pass the `- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler` method, and I also test your anser. my app didi not invoke this method I posted. – aircraft Jan 12 '17 at 06:17
  • Try implementing above code and i am sure you won't face any issues. I have tested this code – Developer Jan 12 '17 at 06:24