如何在iOS应用程序上实现Apple推送通知服务?

Mus*_*afa 3 xcode push-notification apple-push-notifications ios

有没有说明如何整合所有样本项目APNSIPhone,以及如何获得deviceToken?

Dav*_*Ari 24

您需要遵循以下几个简单步骤:

  1. 在您的app delegate的didFinishLaunchingWithOptions中,您应该注册远程通知.请注意,苹果的文档建议每次应用程序运行时注册,因为令牌可能会不时更改.你这样做是通过调用:

    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
    
    Run Code Online (Sandbox Code Playgroud)
  2. 注册远程通知后,将调用应用程序委托中已传递令牌的方法,您需要在应用程序委托中实现此方法并将令牌发送到您的服务器(将向您发送通知).该方法将如下所示:

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
        NSLog(@"device token is: %@",deviceToken);
        [server sendToken:deviceToken];
    }
    
    Run Code Online (Sandbox Code Playgroud)

你也应该实现这个:

    -(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{}
Run Code Online (Sandbox Code Playgroud)
  1. 一旦获得通知,您需要处理通知.您处理收到通知的几种不同场景(应用程序位于后台或前台等),如果应用程序位于前台,处理通知的方法应该在应用程序委托中实现.就是这个:

    -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
        NSLog(@"received notification");
        //handle the notification here
    }
    
    Run Code Online (Sandbox Code Playgroud)

要了解有关userInfo结构的更多信息并涵盖所有不同的方案,请仔细阅读http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/ApplePushService/ApplePushService.html.这只是事情的要点:)