iOS remote push principle and implementation process

Source: Internet
Author: User

? More technical Dry please poke: Listen to the Cloud blog

Push notifications are an essential feature of today's apps. So how do we implement remote push in IOS? What is the remote push principle of IOS? When we do IOS remote push, we encounter a variety of problems. So first, let's get ready for something to push. We need a paid Apple developer account (free to do remote push), and with a developer account, we can go to the Apple developer site and configure the required push-related certificates. Then download the certificate for us to use later, the detailed certificate configuration process, we say below.

First, let's talk about the fundamentals of iOS push notifications:

Apple's push service notification was done by its own dedicated push server APNs (Apple push Notification service), which APNs received a push message from our own application server and pushed the message to the device on the specified IOS. Then the iOS device notifies us of our application, and we will receive a push-back message in the form of a notification or a sound. The premise of iOS remote push is that the iOS device with our application needs to register with the APNs server, and after the successful registration, the APNS server will return us a devicetoken, and we will send this token to our own application server after we obtain this token. When we need to push a message, our application server packages the message in the specified format and then sends it to the APNS server in conjunction with the Devicetoken of the IOS device. Our app maintains a long TCP-based connection with the APNs server, APNs the server pushes the new message to the iOS device, and then displays the push message on the device screen.

Flowchart for device Registration APNs:

Completed the following steps:

1.Device (device) Connect APNs server and carry device serial number (UUID)

2. Successful connection, APNs is packaged and processed to generate Devicetoken and return to registered device (device)

3.Device (device) carries the acquired Devicetoken to our own application server

4. Complete the registration of the device (devices) that need to be pushed on the APNs server and our own application server

Push process diagram:

The push process takes the following steps:

1. First of all, our device has the push function of the application (application to use code Registration message driven), our iOS device in the case of a network connection APNS push server, the connection process, the APNS server will verify the Devicetoken, after the successful connection to maintain a TCP-based The long connection;

2.Provider (our own application server) receives messages that need to be pushed and is packaged together with the Devicetoken of the iOS device being pushed to send to the APNS server;

The 3.APNS server pushes the push message to the specified devicetoken iOS device;

4.iOS device notifies our application after receiving a push message and displays and prompts the user (sound, popup box)

A more intuitive flowchart:

Information Package Structure diagram:

The message body shown is the message structure that our application server (Provider) sends to the APNS server, APNs verifies that the structure is correct and extracts the information, and then pushes the message to the specified iOS device. This structure consists of five parts, the first part is the command identifier, the second part is the length of our Devicetoken, the third part is our Devicetoken string, the last part is the length of the push message body (Payload), the final part is the real message content. , which contains basic information about the push message, such as the message content, how many numbers are displayed in the top right corner of the app icon, and the sounds played when the push message arrives.

Structure of the Payload (message body):

{"     APs": {     "alert": "Listen to the cloud send you a new message",     "badge": 1,     "sound": "Default"     },}

This is actually a JSON structure, the content of the alert tag is displayed on the user's mobile phone push information, the number of badge display (note is the integer) is displayed in the upper right corner of the app icon, the number of unread messages, etc., sound is when the push message delivery is the voice of the mobile phone play , the Defalut is marked with the system default sound.

Here is the push process for the certificate we need to push notifications:

1. First we need to create a new certificate Signing request (i.e. CSR) file

Find keychain Access in the usage tool in the application, select Request certificate from certification authority

Note: Email address, fill in your own developer account, commonly used name, just fill in a remember on the line. Then select Save to disk. Just keep going.

Save location in Tingyun (Specify your own folder, where I select My folder), click Save

Then click Done we will see a certificatesigningrequest.certsigningrequest request file in Tingyun, which is the CSR file we said. At the same time we generate a CSR file, we generate a pair of keys in keychain Access, the name of the common name we filled out just now

2. Configure AppID

To the Apple developer website https://developer.apple.com

Click Account

Select Certificates,identifiers&profiles

Select Identifiers->app IDs click on the + sign above to create an App ID.

Name: Just fill in the APP's name.

App ID Suffix Select the Explicit app ID without a wildcard character

Bundle ID: Fill in the bundle ID of your application must be consistent with your own application.

Select the services you need in the following APP services

We need to push the service, so tick on push notifications

Then click Continue

3. Create a certificate

Certificates need to be created in two ways, one developed, one published, and developed for testing purposes.

Select Development click on the + sign in the upper right corner to create the certificate, we first create the development certificate

Select Apple Push Notification service SSL (Sandbox) and create a push service certificate click Next

The app ID here selects the app ID we just created

Then click Next, Next

Click Choose file here to select the CSR files we just created.

Then click Generate (Generate)

Finally click Download, download the certificate. Place the downloaded certificate in the specified location.

Publish certificate creation and development certificate, select Production->apple Push Notification service SSL (Production) and the same as the development certificate

4. Add Devices:

First select which device you want to add, and then click the "+" sign in the upper-left corner.

Name fill in a device name.

UDID fill in the UDID of the device you need to add the test to.

Then click Next

Then click Register to

Click Done.

5. Find the UDID of the device:

Connect to your computer with your IOS device and open iTunes.

A serial number can be seen at the device summary, and clicking on the serial number will change to UDID.

6. Build the configuration file

There are two kinds of configuration files, one is development, one is release, the development makes us do the test need, release is we need when we publish on AppStore, we all need to build.

Our husband into the development configuration file, select provisioning Profiles->development click on the + sign in the upper right corner.

Select iOS App Development click Next

The app ID here still selects the app ID we just created

Here you choose our Developer's certificate, if you do not know which option is all

Here choose our test equipment, if not in front of the devices inside add can

Just grab a name and download it.

The publish profile is created just like the development configuration file, select Distribution->ad Hoc, and follow the same release profile.

Certificate configuration complete, open the app project we created

Open APPDELEGATE.M file, in-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (NSDictionary *) Add the following code to the Launchoptions method to register the message push

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {//        Override point for customization after application launch. /** Message Push Registration */if ([Uidevice currentdevice].systemversion.floatvalue >= 8.0) {Uiusernotificationsetti NGS *settings = [Uiusernotificationsettings Settingsfortypes:uiusernotificationtypebadge | Uiusernotificationtypesound |        Uiusernotificationtypealert Categories:nil];        [Application registerusernotificationsettings:settings];    [Application registerforremotenotifications]; }else {[Application registerforremotenotificationtypes: (Uiremotenotificationtypebadge | Uiremotenotificationtypesound |    Uiremotenotificationtypealert)]; } return YES; The following method returns the unique identity generated by the ANPs Apple push server/** the device that is returned by the receiving server uniquely identifies token */-(void) Application: (UIApplication *) application    Didregisterforremotenotificationswithdevicetoken: (NSData *) devicetoken{//First run get to Devicetoken time will be longer! The deviceTokens are converted into strings for subsequent use nsstring *token = [Devicetoken description]; NSLog (@ "description%@", token);} The following method is triggered when a message is pushed back to receive a push message when the/** device receives a message from an Apple push server to display the push message */-(void) Application: (UIApplication *) application Didreceiveremotenotification: (nsdictionary *) userinfo{NSLog (@ "UserInfo = =%@", userInfo);} The method above is to receive an error message when registering a push service failure/** registration push service failed */-(void) Application: (UIApplication *) application Didfailtoregisterforremotenotificationswitherror: (Nserror *) error{NSLog (@ "Registration failed%@", error);}

1 <span style="font-family: ‘Microsoft YaHei‘; font-size: 16px;"> </span>

Server-side (Java server)

Server side We need, a suffix for. P12 certificate, as well as the required jar package

How the server-side certificate is generated:

Open the certificate we downloaded earlier and find it in the keychain

Click the right mouse button to select Export

Export the file suffix. P12 to your own computer, you need to enter a password, on the Java server side to use

Java server-side required Jar Package

Java Server-side code:

Import Javapns.back.pushnotificationmanager;import Javapns.back.sslconnectionhelper;import javapns.data.Device;                                Import Javapns.data.payload;public class Pushservice {public static void main (string[] args) {                   try {String Devicetoken = "Eab6df47eb4f81e0aaa93bb208cffd7dc3884fd346ea0743fcf93288018cfcb6";                   The iphone application identifier PayLoad PayLoad = new PayLoad () was pushed;                   Payload.addalert ("Test my Push Message");                   Payload.addbadge (1);                                               Payload.addsound ("Default");                   Pushnotificationmanager Pushmanager = Pushnotificationmanager.getinstance ();                                                         Pushmanager.adddevice ("iphone", Devicetoken);                    Test the push server address: gateway.sandbox.push.apple.com/2195//Product Push server address: gateway.push.apple.com/2195 String host= "gateway.sandbox.push.apple.cOm ";                   Test the Apple push server int port = 2195; String Certificatepath = "/USERS/HSW/DESKTOP/PUSHTEST/PUSHTEST.P12";                                     The certificate that you just exported under Mac system String certificatepassword= "123456"; Pushmanager.initializeconnection (host, Port, Certificatepath,certificatepassword, Sslconnectionhelper.keystore_                                                TYPE_PKCS12);                   Send Push Device client = pushmanager.getdevice ("iphone"); Pushmanager.sendnotification (client, payLoad);                   Push message pushmanager.stopconnection ();                  Pushmanager.removedevice ("iphone");                   } catch (Exception e) {e.printstacktrace ();                    System.out.println ("Push faild!");                  Return                 } System.out.println ("Push succeed!"); }}

iOS remote push principle and implementation process

Related Article

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.