【问题标题】:How to get APNS push notification in background in iOS6?如何在 iOS6 后台获取 APNS 推送通知?
【发布时间】:2025-12-07 20:00:01
【问题描述】:

我正在我的 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];
    }
}

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 好吧,我修改了我的代码如下: - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { NSDictionary *apsInfo = [userInfo valueForKey:@"aps"] ; NSString *fv=[[apsInfo valueForKey:@"alert"] componentsJoinedByString:@""]; UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Alert" message:fv delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; [alert show];},但我也没有在后台看到任何通知。任何线索
    • @Eran :“如果它没有运行,则调用不同的方法。”不同的方法?如果您可以指定该方法,这对其他来这里的人会很有帮助。
    • @S.Philip 感谢您的评论,我更新了答案。