远程推送 iphone推送消息 实例

原文地址:http://mobiforge.com/developing/story/programming-apple-push-notification-services

英语太烂就不翻译了....

 

 正常的iPhone刷系统之后,是没有设备证书和密钥的。这就是为什么iPhone会需要连接到 iTunes上进行激活——激活过程中,Apple会分配给每台iPhone独一无二的设备证书(device certificate)和密钥(key)。(本人由于没有意思到这个 一直收到 "未找到应用程序的"aps-environment" 的权利字符串")

 

 

One of the key limitations of the iPhone is its constraint on running applications in the background. Because of this, applications cannot keep running in the background when the user switches to another application. So, applications that require a constant state of connectivity (such as social networking applications) will not be able to receive timely updates.

To remedy this limitation, Apple released the Apple Push Notification Service (APNs). The APNs is a service that allows your device to be constantly connected to Apple's push notification server. When you want to send a push notification to an application installed on the users' devices, you (the provider) can contact the APNs so that it can deliver a push message to the particular application installed on the intended device.

In this article, you will learn how to perform the various steps needed to create an iPhone application that uses the APNs.

 

Generating a Certificate Request

The first step to using the APNs is to generate a certificate request file so that you can use it to request for a development SSL certificate later on.

1. Launch the Keychain Access application in your Mac OS X.

2. Select Keychain Access'Certificate Assistant'Request a Certificate From a Certificate Authority (see Figure 1):

 

1
Figure 1. Generating a certificate request

3. Enter the information required and check the Saved to disk option. Click Continue (see Figure 2).

 

2


Figure 2. Saving the certificate request to disk

4. Save the certificate request using the suggested name and click Save (see Figure 3): Click Done in the next screen.

3
Figure 3. Naming the certificate request

Creating an App ID

Each iPhone applications that uses the APNs must have a unique application ID that uniquely identifies itself. In this step, you will learn how to create an App ID for push notification.

1. Sign in to the iPhone Developer Program at: http://developer.apple.com/iphone/. Click on the iPhone Developer Program Portal on the right of the page (see Figure 4).

4
Figure 4. Launching the iPhone Developer Program Portal

2. You should see the welcome page (see Figure 5).

5
Figure 5. The welcome screen of the iPhone Developer Program Portal

3. Click on the App IDs tab on the left and then click on the New App ID button (see Figure 6).

6
Figure 6. Clicking on the App ID tab

4. Enter "PushAppID" for the Description and select Generate New for the Bundle Seed ID. For the Bundle Identifier, enter net.learn2develop.MyPushApp. Click Submit (see Figure 7).

7
Figure 7. Creating a new App ID

5. You should now see the App ID that you have created (together with those you have previously created) (see Figure 8).

8
Figure 8. Viewing the newly created App ID

Configuring an App ID for Push Notifications

Once an App ID is created, you need to configure it for push notifications.

1. To configure an App ID for push notification, you need to click the Configure link displayed to the right of the App ID. You will now see the option (see Figure 9).

9
Figure 9. Configuring an App ID for push notification service

Check the Enable for Apple Push Notification service option and click the Configure button displayed to the right of the Development Push SSL Certificate.

2. You will now see the Apple Push Notification service SSL Certificate Assistant screen. Click Continue (see Figure 10).

10
Figure 10. The Apple Push Notification service SSL Certificate Assistant screen

3. Click the Choose File button to locate the Certificate Request file that you have saved earlier. Click Generate (see Figure 11).

11
Figure 11. Generating the SSL certificate

4. Your SSL Certificate will now be generated. Click Continue (see Figure 12).

12
Figure 12. The APNs SSL certificate that is generated

5. Click the Download Now button to download the SSL Certificate. Click Done (see Figure 13).

13
Figure 13. Downloading the certificate generated

6. The SSL Certificate that you download is named aps.developer.identity.cer. Double-click on it to install it in the Keychain Access application (see Figure 14). The SSL certificate will be used by your provider application so that it can contact the APNs to send push notifications to your applications.

14
Figure 14. Installing the generated certificate into the Keychain Access application

Creating a Provisioning Profile

The next step is to create a provisioning profile so that your application can be installed onto a real device.

1. Back in the iPhone Development Program Portal, click on the Provisioning tab and click on the New Profile button (see Figure 15).

15
Figure 15. Selecting the Provisioning tab

2. Type in MyDevicesProfile as the profile name. Select PushAppID as the App ID. Finally, check all the devices that you want to provision (you can register these devices with the iPhone Developer Program Portal through the Devices tab). Click Submit (see Figure 16).

16
Figure 16. Creating a new provisioning profile

3. The provisioning profile will now be pending approval. After a while, you will see it appear. Click on the Download button to download the provisioning profile (see Figure 17).

17
Figure 17. Pending the approval of the provisioning profile

4. The downloaded provisioning profile is named MyDevicesProfile.mobileprovision.

Provisioning a Device

With the provision profile created, you will now install it onto a real device.

1. Connect your iPhone or iPod Touch to your Mac.

2. Drag and drop the downloaded MyDevicesProfile.mobileprovision file onto the Xcode icon on the Dock.

3. Launch the Organizer application from within Xcode and select the device currently connected to your Mac. You should see the MyDevicesProfile installed on the device (see Figure 18).

18
Figure 18. Viewing the installed provisioning profile

Creating the iPhone Application

1. In Xcode, create a new View-Based Application project and name it as ApplePushNotification.

2. Drag and drop a WAV file (shown as beep.wav in this example) onto the Resources folder in Xcode (see Figure 19).

19
Figure 19. Adding a WAV file to the project

3. Expand on the Targets item in Xcode and select the ApplePushNotification item. Press Command-I. In the Info window, click the Properties tab (see Figure 20).

20
Figure 20. Entering the App ID for the application

In the Identifier textbox, type <net.learn2develop.MyPushApp.

4. Click on the Build tab and type "Code Signing" in the search box. In the Any iPhone OS Device item, select the profile as shown in Figure 21:


Figure 21. S21electing the profile for code signing

 

5. In the ApplePushNotificationAppDelegate.m file, type the following code in bold:

 

#import "ApplePushNotificationAppDelegate.h"
#import "ApplePushNotificationViewController.h"
 
@implementation ApplePushNotificationAppDelegate
 
@synthesize window;
@synthesize viewController;
 
- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
 
    NSLog(@"Registering for push notifications...");    
    [[UIApplication sharedApplication] 
        registerForRemoteNotificationTypes:
        (UIRemoteNotificationTypeAlert | 
         UIRemoteNotificationTypeBadge | 
         UIRemoteNotificationTypeSound)];
 
}
 
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { 
 
    NSString *str = [NSString 
        stringWithFormat:@"Device Token=%@",deviceToken];
    NSLog(str);
 
}
 
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 
 
    NSString *str = [NSString stringWithFormat: @"Error: %@", err];
    NSLog(str);    
 
}
 
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
 
    for (id key in userInfo) {
        NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
    }    
 
}
 
- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}
@end

 

///

 

6. Press Command-R to test the application on a real device. Press Shift-Command-R in Xcode to display the Debugger Console window. Observe carefully the device token that is printed (see Figure 22). In the figure below, the token is: 38c866dd bb323b39 ffa73487 5e157ee5 a85e0b7c e90d56e9 fe145bcc 6c2c594b. Record down this device token (you might want to cut and paste it into a text file).

22
Figure 22. Viewing the device token for push notification

7. If you go to the Settings application on your iPhone/iPod Touch, you will notice that you now have the Notifications item (see Figure 23).

23
Figure 23. Viewing the Notifications item in the Settings application

Creating the Push Notification Provider

A Push Notification provider is an application written by the application's developer to send push notifications to the iPhone application through the APNs.

Here are the basic steps to send push notifications to your applications via the Apple Push Notification Service (APNs):
1. Communicate with the APNs using the SSL certificate you have created earlier.
2. Construct the payload for the message you want to send.
3. Send the push notification containing the payload to the APNs.

The APNs is a stream TCP socket that your provider can communicate using a SSL secured communication channel. You send the push notification (containing the payload) as a binary stream. Once connected to the APNs, you should maintain the connection and send as many push notifications as you want within the duration of the connection.

Tip: Refrain from opening and closing the connections to the APNs for each push notification that you want to send. Rapid opening and closing of connections to the APNs will be deemed as a Denial-of-Service (DOS) attack and may prevent your provider from sending push notifications to your applications.

The format of a push notification message looks like Figure 24 (figure from Apple's documentation):

24
Figure 24. Format of a push notification message

For more details, please refer to Apple Push Notification Service Programming Guide.
The payload is a JSON formatted string (maximum 256 bytes) carrying the information you want to send to your application. An example of a payload looks like this:

{
    "aps": { 
        "alert" : "You got a new message!" ,
        "badge" : 5, 
        "sound" : "beep.wav"},
     "acme1" : "bar", 
     "acme2" : 42
}

To save yourself the trouble in developing a push notification provider from scratch, you can use thePushMeBaby application (for Mac OS X) written by Stefan Hafeneger (Get it here).

1. Open the PushMeBaby application in Xcode.

2. Right-click on the Resources folder in Xcode and select Add Existing Files…. Select theaps.developer.identity.cer file that you have downloaded earlier (see Figure 25).

25
Figure 25. Adding the SSL certificate to the application

3. In the ApplicationDelegate.m file, modify the code as shown in bold below:

- (id)init {
    self = [super init];
    if(self != nil) {
        self.deviceToken = @"38c866dd bb323b39 ffa73487 5e157ee5 a85e0b7c e90d56e9 fe145bcc 6c2c594b";
 
        self.payload = @"{/"aps/":{/"alert/":/"You got a new message!/",/"badge/":5,/"sound/":/"beep.wav/"},/"acme1/":/"bar/",/"acme2/":42}";
 
        self.certificate = [[NSBundle mainBundle] 
            pathForResource:@"aps_developer_identity" ofType:@"cer"];
    }
    return self;
}

4. Press Command-R to test the application. You will be asked to grant access to the certificate. Click Always Allow (see Figure 26):

26
Figure 26. Granting access to the SSL certificate

On the iPhone/iPod Touch, ensure that the ApplePushNotification application is not running. To send a message to the device, click the Push button. The server essentially sends the following message to the Apple Push Notification server:

{
    "aps": { 
        "alert" : "You got a new message!" ,
        "badge" : 5, 
        "sound" : "beep.wav"},
     "acme1" : "bar", 
     "acme2" : 42
}

5. If the message is pushed correctly, you should see the notification as shown in Figure 27.

27
Figure 27. Receiving a Push Notification message

6. If you now debug the ApplePushNotification application by pressing Command-R and send a push message from the PushMeBaby application, the Debugger Console window will display the following outputs:

2009-11-24 21:11:49.182 ApplePushNotification[1461:207] key: acme1, value: bar
2009-11-24 21:11:49.187 ApplePushNotification[1461:207] key: aps, value: {
    alert = "You got a new message!";
    badge = 5;
    sound = "beep.wav";
}
2009-11-24 21:11:49.191 ApplePushNotification[1461:207] key: acme2, value: 42

Summary

In this article, you have seen the various steps required to build an iPhone application that utilizes Apple's Push Notification service. I am interested to know how you are using the APNs for your application. Use the comment feature below to share with us!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: iOS消息推送 APNs 是指苹果公司提供的一种用于向移动设备发送远程通知的服务。而使用 Java 实现 HTTP/2 协议发送推送消息可以通过以下步骤完成。 首先,我们需要使用 Java 开发一个 HTTP/2 客户端,以实现与 APNs 服务器的通信。我们可以使用 okhttp、netty 或者 java-http-client 等库来实现这个客户端。 其次,我们需要获取 APNs 服务器的推送地址和凭证认证信息。推送地址常见的有两个,分别是开发环境和生产环境。在获取推送地址之后,我们还需要生成一个包含认证信息的 JWT(JSON Web Tokens),以进行身份验证。 然后,我们可以使用 Java 客户端向 APNs 服务器发送 HTTP/2 请求。请求的内容应包括推送通知的 payload 和设备的设备标识符(Device Token)等信息。设备标识符是由 APNs 服务器为每个设备生成的唯一标识符,用于指定接收消息的设备。 最后,我们可以根据 APNs 服务器的响应来判断推送是否成功。APNs 服务器会返回一个包含推送结果的响应,其中包括推送是否成功以及失败的原因。 总之,使用 Java 实现 HTTP/2 协议发送 iOS 消息推送 APNs,需要开发一个符合 HTTP/2 协议的客户端,生成凭证信息并发送请求。通过与 APNs 服务器的通信,可以将推送消息发送到指定的 iOS 设备上。 ### 回答2: iOS消息推送(APNs)是苹果公司提供的一种服务,用于将推送通知发送到iOS设备上的应用程序。实现APNs推送的一种方法是使用HTTP/2协议发送请求。 在Java中,可以使用一些第三方库来实现使用HTTP/2协议发送APNs消息推送。其中,使用Netty库是一个常见的选择。 首先,你需要引入Netty库的相关依赖项,并创建一个Netty的客户端连接。 然后,你需要创建APNs推送的请求和消息内容。APNs消息使用JSON格式进行发送,你需要构建一个JSON对象来包含推送的内容。这个内容可以包括通知标题、内容、图标等。 接下来,你需要将JSON对象编码为二进制数据,并发送给APNs服务器。此时,你可以使用Netty库提供的HTTP/2的客户端请求来发送。 发送请求的过程包括建立连接、发送帧、处理响应等步骤。你需要设置请求的方法、URL、Headers以及Payload(即消息内容的二进制数据)。 最后,你需要在接收到APNs服务器的响应后,进行对应的处理和错误处理。常见的响应包括成功响应和错误响应。 总结起来,实现使用HTTP/2协议发送APNs消息推送的过程,包括建立连接、构建JSON消息、编码为二进制数据、发送请求、处理响应等步骤。通过使用Netty库,可以简化这个实现过程,并提供了更好的性能和可扩展性。 ### 回答3: 在iOS中,APNS(Apple Push Notification Service)是一种用于向苹果设备(如iPhone、iPad、iPod Touch等)推送消息的服务。而在Java中,可以使用HTTP/2协议来实现发送APNS通知。 HTTP/2是一种基于HTTP/1.1的进化版本,其在性能和效率上有所提升。使用Java实现HTTP/2协议发送APNS通知的步骤如下: 1. 首先,需要准备APNS证书。在苹果开发者账号中创建一个推送证书,并将其导出为.p12文件。 2. 将.p12文件转换为Java可用的密钥和证书形式。可以使用Java的KeyTool工具来完成此步骤。 3. 使用Java的HTTP/2库,如Jetty或Netty,建立与APNS服务器的HTTP/2连接。这些库可提供与APNS服务器之间的双向通信。 4. 在建立连接后,可以使用HTTP/2的帧和流的概念向APNS服务器发送推送通知。可以使用Jetty或Netty提供的API来创建和发送HTTP/2帧。 5. 在发送通知时,需要将推送的相关信息,如设备令牌、推送内容等,封装为HTTP/2的帧数据发送到APNS服务器。 6. APNS服务器收到推送请求后,会根据设备令牌等信息将通知推送给相应的设备。 总之,使用Java实现HTTP/2协议发送APNS通知需要准备证书、使用HTTP/2库建立连接,并利用API创建和发送HTTP/2帧,最后将推送信息发送给APNS服务器。这样就可以通过HTTP/2协议向iOS设备推送消息了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值