Implementation and Discussion of iPhone message push mechanism apns

Source: Internet
Author: User
Tags openssl x509 pkcs12

In the last two days, I have studied the message push mechanism for IOS. It is still interesting to study this thing.

Push principle:

The working mechanism of push can be summarized

In the figure, provider refers to the push server of an iPhone software. In this article, I will use. NET as the provider.
Apns is the abbreviation of Apple push notification service (Apple push server). It is an apple server.

It can be divided into three stages.

Phase 1: the. NET application packs the message to be sent and the identifier of the target iPhone and sends it to apns.
Stage 2: apns searches for the iPhone with the corresponding identifier in its registered PUSH Service iPhone list and sends the message to the iPhone.
Stage 3: The iPhone transmits the sent message to the corresponding application, and a push notification is displayed according to the settings.

We can see from.

1. First, the application registers for message push.

2. for iOS and apns servers, devicetoken is required. The application accepts devicetoken.

3. The application sends the devicetoken to the push server.

4. The server program sends a message to the apns service.

5. The apns Service sends messages to the iPhone application.

Both the iPhone client and apns, provider and apns, must be connected through a certificate. Below I will introduce several certificates used.

Several certificates:

1. *. certsigningrequest File

1. Generate a Certificate Signing Request (CSR ):

2. Enter your mailbox and common name. Enter pushchat here. Select Save to hard disk.

In this way, a pushchat. certsigningrequest file is generated in the response.

Ii. Generate the *. p12 File

1. Export the key and enter your password.

Enter your password:

In this way, a pushchatkey. p12 file is generated.

3. Create an app ID and SSL Certificate file

1. log on to the IOS provisioning portal with your paid Apple account. Create an app ID.

Description: Enter pushchat

Bundle seed ID: generate new by default

Bundle identifier: Enter com. mysoft. pushchat

Click to submit

This will generate the following record:

Click Configuration:

The following page appears. Click continue.

Here we select the previously generated pushchat. certsigningrequest file and click Generate.

Generating

After the generation is completed, download it. The name is aps_developer_identity.cer.

Click Finish and you will find the status changed to enabled.

So far, we have generated three files.

1. pushchat. certsigningrequest

2. pushchatkey. p12

3. aps_developer_identity.cer

Now we create a simple iPhone application.

1. Open xcode and choose to create a view-based application. The name is as follows:

2. Add the following code to the didfinishlaunchingwitexceptions method in pushchatappdelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window.rootViewController = self.viewController;    [self.window makeKeyAndVisible];     // Let the device know we want to receive push notifications    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:        (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];     return YES;} 

The registerforremotenotificationtypes method is used to notify the application to receive push notifications.

3. When running in xcode, the following prompt box is displayed:

Select OK. Indicates that the application has enabled the Message notification service.

In the pushchatappdelegate. m code, add the following method to obtain the devicetoken:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{    NSLog(@"My token is: %@", deviceToken);} - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{    NSLog(@"Failed to get token, error: %@", error);} 

After obtaining the devicetoken, we can submit it to the. NET application through the WebService. Here I simply process it, print it directly, and copy it to the. NET application environment for use.

The. NET application that sends the notification needs to know the devicetoken and a certificate to connect to apns.

This certificate can be obtained from the two files we generated earlier.

Use OpenSSL to generate a certificate file for. NET and apns communications.

1. Convert aps_developer_identity.cer to aps_developer_identity.pem format.

OpenSSL X509-In aps_developer_identity.cer-inform der-out aps_developer_identity.pem-outform PEM

2. to convert a private key in p12 format to PEM, you need to set the password four times. Here the password is set to ABC123.

OpenSSL PKCS12-nocerts-out pushchat_noenc.pem-In pushchat. p12

3. Use Certificate and the key to create a file in PKCS #12 format.

OpenSSL PKCS12-export-In aps_developer_identity.pem-inkey pushchat_noenc.pem-certfile pushchat. certsigningrequest-name "aps_developer_identity"-out aps_developer_identity.p12

In this way, we get the certificate file used in the. NET application: aps_polic_identity.p12.

Send notifications in. NET applications.

There is an open-source Class Library: apns-sharp.

The address is http://code.google.com/p/apns-sharp /.

We can download the source code and make corresponding adjustments to the jdsoft. Apple. apns. notifications in it.

We adjusted the jdsoft. Apple. apns. configurations. Test code based on devicetoken and p12file, as shown in.

In this case, OK.

Effect:

Notification code:

            for (int i = 1; i <= count; i++)            {                //Create a new notification to send                Notification alertNotification = new Notification(testDeviceToken);                                alertNotification.Payload.Alert.Body = string.Format("Testing {0}...", i);                alertNotification.Payload.Sound = "default";                alertNotification.Payload.Badge = i;                                                //Queue the notification to be sent                if (service.QueueNotification(alertNotification))                    Console.WriteLine("Notification Queued!");                else                    Console.WriteLine("Notification Failed to be Queued!");                //Sleep in between each message                if (i < count)                {                    Console.WriteLine("Sleeping " + sleepBetweenNotifications + " milliseconds before next Notification...");                    System.Threading.Thread.Sleep(sleepBetweenNotifications);                }            }

The following figure shows an iPad shot on a mobile phone:

Summary:This article mainly describes in detail how to implement the IOS message push mechanism and how to send messages through a. NET application.Send messages to iOS apps.

Author: Zhu Yulin
Source: http://zhuqil.cnblogs.com
The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.