如何在iOS6的后台获取APNS推送通知?

时间:2013-12-10 06:44:37

标签: ios6 push-notification apple-push-notifications

我正在iOS应用程序中实现APNS。我在前台收到苹果推送通知,但当我的应用程序进入后台或非活动模式时,我的应用程序没有收到任何推送通知。

我尝试过的代码如下:

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

    UIApplicationState state = [application applicationState];
    if (state == UIApplicationStateActive) {
        NSLog(@"active");
        NSDictionary *apsInfo = [userInfo valueForKey:@"aps"];

        NSString *fv=[[apsInfo valueForKey:@"alert"] componentsJoinedByString:@""];
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Active" message:fv delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
    }else if (state == UIApplicationStateBackground){
        NSLog(@"background");
        NSDictionary *apsInfo = [userInfo valueForKey:@"aps"];

        NSString *fv=[[apsInfo valueForKey:@"alert"] componentsJoinedByString:@""];
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Background" message:fv delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
    }
    }else{
        NSLog(@"Inactive");
         NSDictionary *apsInfo = [userInfo valueForKey:@"aps"];
         NSString *fv=[[apsInfo valueForKey:@"alert"] componentsJoinedByString:@""];
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Inactive" message:fv delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
    }
}

请告诉我哪里出错了或遗失了什么。

1 个答案:

答案 0 :(得分:2)

当应用程序处于后台或处于非活动状态时,您不应以编程方式显示通知。当应用处于其中一种状态时,iOS会自动显示alert字典的aps文字,并且只有在显示通知并由用户点按以打开您的应用后才会调用您的代码。< / p>

如果用户未通过点击通知打开您的应用,您的代码将永远不会被调用。此外,仅当应用程序处于活动状态或在后台运行时,才会调用didReceiveRemoteNotification方法。如果它没有运行,则会调用另一种方法 - application:didFinishLaunchingWithOptions