Apple Push Notification Service usage summary.

Source: Internet
Author: User
Tags app service openssl openssl x509 ssl certificate

From http://blog.csdn.net/lifengzhong/article/details/7737028# Apple information Push service (Apple push Notification services), Is the message push service provided by Apple. The push form includes the top message bar, sound, and badge number () with APNs, and the application can receive program-related messages in any state (including the running state not running,foreground and background), because in most cases There is at most one app in iOS that can be in active state, so APNs is a great convenience for your app's interactions.

A: Introduction

Before using APNs, there are a few things you need to know:

1:apns is free of charge. You can apply for a APNs certificate as long as you have a developer account.

2:apns is unreliable, and Apple does not guarantee the reliability of the information push.

3:apns has a limit on the size of the message, and the total capacity cannot exceed 256 bytes.


Clear the above three, you should be aware of the application scenarios for APNs.


The APNs workflow is shown in the following diagram:



1 & 2: When the user installs the app for the first time and starts it for the first time, it will pop up a dialog box prompting the app to open the push, whether it is allowed, and if so, the app will get a hardware token.

There are three points to note:

First, the token is the only device-related, the same token used by different applications on the same device;

Second, when the application is uninstalled and then reinstalled, the confirmation dialog box will no longer appear and automatically inherit the settings information from the previous installation;

Third, push settings can be changed in Settings-notifications. You can choose to turn on one or more of the message boxes, sounds, and badge number.


3: Application will receive tokens sent to the server, that is, the source of APNS messages.

4: The application server sends messages to Apple's messaging server through tokens and certificates.

5: Apple sends the received message to the corresponding app on the corresponding device.

6: If the app is not in the active state (not started or backgroud), the default setting, the top of the screen will pop up a message box, and a sound prompt, click the Change message box will enter the app, if not click on the app icon will have badge number appears.


Second: Use steps

The use of APNs is not complex, but error-prone links are more, especially the part of the certificate application, to pay special attention.

Follow the steps I've actually done in the tutorial to illustrate:

Preparatory work:

A: A Xcode project, we'll name it mypushchat, and a corresponding app ID.

B: An iOS device that can be used for debugging (APNs only works on the physical device and the emulator does not run)


Step1:

In application-use tools, open keychain Access (Keychain access), as shown in the following illustration:




In the next dialog box, select Save to disk, the message can be filled in, the name is named Mypushchat



Click "Continue" to set the file name to "Mypushchat" and click Save. In this way, you will get a file called "Mypushchat.certsigningrequest", which should be kept properly.


The private key is everywhere from the CSR file you just created, as shown in the following figure:


Name the exported file mypushchatkey.p12, and enter the password, keeping this password in mind, let's set it to 123456ABC.

At this point, we already have the file mypushchat.certsigningrequest, and MYPUSHCHATKEY.P12


Step2:

In the app IDs, find the mypushchat corresponding to the AppID, click on the right "Configure" button, tick the following image to select the box:


Click on the Configure button on the right of "development Push SSL Certificate" to apply the development version to the test, valid for only one year, and only use Apple's APNs test server. You need to request a distributions version of the certificate when the app is published. Development and the distribution version of the certificate obtained token is not the same. The popup box looks like this:


Upload "Mypushchat.certsigningrequest" and click Generate, a moment after the certificate is generated, download, named "Aps_developer_identity.cer".


Step3:

Open Provision Portal, click New provision, name provision file "Mypushchat", select the corresponding app ID and device and download. Get the file mypushchat.provision. Double-click Import this mypushchat.provision file, if everything is OK, it will pop up Orgnizer, and the display interface is as follows:



Step4:

Save the above files to the desktop. Open the console and switch to the desktop.

First convert Aps_developer_identity.cer to Mypushchat.cert

Command: OpenSSL x509-in aps_developer_identity.cer-inform der-out Mypushchatcert.pem


Then convert the private key file to Mypushchatkey.pem

Command:

OpenSSL pkcs12-nocerts-out mypushchatkey.pem-in MYPUSHCHATKEY.P12

Enter Import Password:

The password entered here is the password previously set for the private key: 123456ABC

MAC verified OK

Enter PEM Pass Phrase:

You must enter a new password here, we set to 123456ABC

Verifying-enter PEM Pass Phrase:


Next, synthesize Mypushchatkey.pem and Mypushchatcert.pem into a PEM file:

Command: Cat Pushchatcert.pem PUSHCHATKEY.PEM > Ck.pem


Finally, test the resulting CK.PEM file

Run First:

Command: Telnet gateway.sandbox.push.apple.com 2195

If the network is OK, the following appears, CTRL + C terminates the connection.

Trying 17.172.232.226 ...

Connected to Gateway.sandbox.push-apple.com.akadns.net.

Escape character is ' ^] '.


Then test the connection using SSL

Command: OpenSSL s_client-connect gateway.sandbox.push.apple.com:2195-cert mypushchatcert.pem-key MyPushChatKey.pem

After entering the password 123456abc, if everything is OK, there will be a lot of output, you will be able to enter several characters, after the carriage return, the connection will be interrupted.


To this, the most tedious and error-prone process has been completed, certificate-related work to this end, into the coding phase ~


Step5:

1:

Add the following code to the APPDELEGATE.M didfinishlaunchingwithoptions in the project Mypushchat

[plain] view plain copy print? [[UIApplication Sharedapplication] registerforremotenotificationtypes: (Uiremotenotificationtypebadge | Uiremotenotificationtypesound | Uiremotenotificationtypealert)];

[[UIApplication sharedapplication] Registerforremotenotificationtypes:
		(Uiremotenotificationtypebadge | Uiremotenotificationtypesound | Uiremotenotificationtypealert)];

This sentence code for the first time when the application Pop-up dialog box to let the user confirm whether to open the message push, this sentence registered message type has badgenumber, sound, top message box. One or more of these can be selected.


2:

Add the following code to the Appdelegate:

[plain] view plain copy print? -(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); }

-(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);
}
If the token is obtained successfully, the output in the following format will be in the runtime console:

My token is:<740f4707 bebcf74f 9b7c25d4 8e335894 5f6aa01d a5ddb387 462c7eaf 61bb78ad>

Save the angle bracket content and use it later

Similarly, add the following code to the Appdelegate

[plain] view plain copy print?-  (void)  application: (uiapplication *) application  didreceiveremotenotification: (nsdictionary *) userinfo    {        if  ( application.applicationState == UIApplicationStateActive )  {            //  programs are subject to push notifications during Operation             nslog ("%@",  [[userinfo objectforkey: @ "APS"]  objectforkey: @ "alert"]);       } else {            //Program for push notifications        }  }  in Run status  

-(void) Application: (UIApplication *) application didreceiveremotenotification: (nsdictionary *) userInfo 
{
    if (application.applicationstate = = uiapplicationstateactive) {
        //program is subject to push notification
        NSLog ("%@", [UserInfo Objectforkey: @ "APS"] Objectforkey: @ "alert"]);
    } else {
        //program is subject to push notification in run state
    }
}
The above code handles how the app receives push notifications in both the running and non-active states.


3:

Download the PHP sample program, set the Devicetoken field to the token you just saved, and take care to remove the space.

Set Password to 123456ABC, set the message to the content you want to set, save it, and then enter the PHP source path under the command line to run PHP simplepush.php


If the character is good enough, your device will immediately ring a sound ~



Three: Other precautions

1: You can use the following code to determine which types of message notifications are turned on:

[plain] view plain copy print?   Uiremotenotificationtype enabledtypes = [[UIApplication sharedapplication] enabledremotenotificationtypes]; if (Enabledtypes & Uiremotenotificationtypebadge) {//Open badge number} if (Enabledtypes & Uiremotenotificati Ontypesound) {//Turn on Sound} if (Enabledtypes & Uiremotenotificationtypealert) {//Open alert}

Uiremotenotificationtype enabledtypes = [[UIApplication sharedapplication] enabledremotenotificationtypes];
if (Enabledtypes & Uiremotenotificationtypebadge) {
//Open badge number
}
if (Enabledtypes & Uiremotenotificationtypesound) {
//Turn on sound
}
if (Enabledtypes & Uiremotenotificationtypealert) {
/ /Open Alert
}

2: Push server is recommended to use Javapns, it is easy to use, note that the certificate file used is not PEM, but the P12 format, the specific generation method is:

One: Generate the CSR file (IBID.)

II: Generate CERT file on Apple website via CSR (IBID.)

Three: Double-click Import generated cert file, in keychain, select both the private key of the CSR and the SSL certificate just imported, right-click Export, Save As P12

Same as other procedures


3: If you are sure, you can directly use the distribution version of the certificate and provision file, but the online server has certain restrictions, if used improperly, will be Apple when DDoS ban off.


4: Apple's push server will return a send result to the application server, and for the target that has failed, the app service side needs to be processed.


5: The transmitted message is in JSON format, where you can add your own fields, but again, the total size cannot exceed 256 bytes.



Reference documents

Apple Push Notification Service tutorial

Apple Push Notification Services tutorial:part 1/2

APNs Official documents

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.