iOS / Obj-C - didReceiveRemoteNotification语句没有触发?

时间:2017-07-20 16:48:16

标签: ios objective-c push-notification

我正在尝试发布本地通知,以便在收到远程通知时更改标签栏项目上的徽章编号。如果在应用程序打开时收到通知,则下面的其他声明会完全触发。但是,如果应用程序在后台,我的前两个if语句似乎永远不会触发?

AppDelegate.m

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

    if(application.applicationState == UIApplicationStateInactive) {

        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushNotification" object:nil userInfo:userInfo];

        NSLog(@"Inactive - the user has tapped in the notification when app was closed or in background");

        completionHandler(UIBackgroundFetchResultNewData);
    }
    else if (application.applicationState == UIApplicationStateBackground) {

        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushNotification" object:nil userInfo:userInfo];

        NSLog(@"application Background - notification has arrived when app was in background");
        NSString* contentAvailable = [NSString stringWithFormat:@"%@", [[userInfo valueForKey:@"aps"] valueForKey:@"content-available"]];

        if([contentAvailable isEqualToString:@"1"]) {

            NSLog(@"content-available is equal to 1");
            completionHandler(UIBackgroundFetchResultNewData);
        }
    }
    else {

        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushNotification" object:nil userInfo:userInfo];

        NSLog(@"application Active - notication has arrived while app was opened");

        completionHandler(UIBackgroundFetchResultNewData);
    }
}

或:我也尝试过以下代码,同样的问题......

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

    UIApplicationState state = [application applicationState];
    if (state == UIApplicationStateActive) {

        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushNotification" object:nil userInfo:userInfo];

        NSLog(@"App notification received!");
        // do stuff when app is active

    }else{

        static int i=1;
        [UIApplication sharedApplication].applicationIconBadgeNumber = i++;


        NSLog(@"App notification received background!");
    }
}

FIX(对于那些使用Drupal的人):将以下内容添加到push_notifications.admin.inc(Drupal推送通知文件)**

$payload['content-available'] = 1;

1 个答案:

答案 0 :(得分:1)

在推送通知有效内容中添加content-available=1Further reading