IOS remote push principle and implementation process, ios principle process

Source: Internet
Author: User
Tags key string

IOS remote push principle and implementation process, ios principle process

Refer to the following link for more technical tips: Alibaba Cloud blog

Pushing notifications is an essential feature of today's applications. In iOS, how do we implement remote push? What is the principle of iOS remote push? During iOS remote push, we encounter various problems. First, let's prepare something for pushing. We need a paid Apple developer account (free remote push is not allowed). With the developer account, we can go to the Apple developer website and configure the required push certificate. Then download the Certificate for later use. Let's talk about the detailed certificate configuration process.

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

Apple's Push service Notification is completed by its own dedicated Push server APNs (Apple Push Notification service, the process is that APNs receives the pushed message from our application server and pushes the message to the specified iOS device, then, the iOS device sends a notification to our application. We will receive the pushed message in the form of a notification or sound. The premise of iOS remote push is that the iOS device with our application needs to register with the APNs server. After the registration is successful, the APNs server will return a devicetoken to us, after obtaining the token, we will send the token to our app server. When we need to push a message, our app server packs the message in the specified format and sends it to the APNs server together with the devicetoken of the iOS device. Our application maintains a TCP-based persistent connection with the APNs server. The APNs server pushes new messages to the iOS device and then displays the pushed messages on the device screen.

Flowchart of device registration APNs:

Complete the following steps:

1. Device connects to the APNs server and carries the Device serial number (UUID)

2. The connection is successful. After APNs is packaged and processed, the devicetoken is generated and returned to the registered Device)

3. The Device carries the acquired devicetoken to our app server.

4. register the Device to be pushed on the APNs server and our own application server.

Push process diagram:

The push process follows the steps below:

1. first, our device has an application with the push function installed (the application must use code to register for message pushing), and our iOS device will connect to the APNs push server when there is a network, during the connection, the APNS server verifies the devicetoken and maintains a TCP-based persistent connection after the connection is successful;

2. The Provider (our app server) receives the message to be pushed and sends it together with the devicetoken of the iOS device to the APNS server;

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

4. the iOS device notifies our app after receiving the PUSH message and displays and prompts the user (sound and pop-up box)

Intuitive flowchart:

Information Package Structure:

The displayed message body is the message structure sent by our application server (Provider) to the APNs server. After APNs verifies that the structure is correct and extracts the information, then, push the message to the specified iOS device. This struct consists of five parts: The first part is the command identifier, the second part is the length of our devicetoken, and the third part is our devicetoken string, the fourth part is the length of the push message body (Payload), and the last part is the real message content, which contains the basic information of the push message, such as the message content, how many digits are displayed in the upper right corner of the application Icon and the playing sound when the PUSH message arrives?

Payload (Message Body) structure:

 

{"Aps": {"alert": "", "badge": 1, "sound": "default "},}

 

This is actually a JSON structure. The content of the alert tag is the push information that will be displayed on the user's mobile phone. The number of badge labels is displayed (integer type) is the number of unread messages displayed in the upper-right corner of the application Icon, indicating the number of unread messages. sound indicates that when the push information is delivered, it indicates the sound played by the mobile phone. If defalut is passed, it indicates that the system default sound is used.

The following is the process of pushing certificates required for pushing notifications:

1. First, we need to create a Request file for Certificate Signing Request (that is, CSR ).

In the tools used in the application, find the key string access and select to request the certificate from the Certificate Authority

Note: Fill in your developer account and common name as the email address. Just fill in one email address and remember it. Then select to store the data to the disk. Continue.

The storage location is in tingyun (specify your own folder, here I select my folder), click Storage

After clicking finish, we will see a request file for CertificateSigningRequest. certSigningRequest in tingyun, that is, the CSR file we mentioned. When we generate the CSR file, a pair of keys will be generated during key string access. The name is the common name we just entered.

2. Configure AppID

Go to Apple developer website https://developer.apple.com

Click Account

Select Certificates, identifiers & Profiles

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

Name: Enter the App Name.

App ID Suffix select and explain it App ID without wildcards

Bundle ID: the Bundle ID of your application must be consistent with that of your application.

Select the desired service in the following App Services

We need to Push the service, so we checked the Push Notifications.

Then click continue

3. Create a certificate

Two types of certificates must be created: development, release, and test.

Select Development and click the plus sign in the upper right corner to create a certificate. First, create a Development certificate.

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

Select the App ID we just created.

Click Next and next.

Click Choose File and select the CSR File we just created.

Click Generate)

Click Download to download the certificate. Place the downloaded certificate to the specified location.

 

Create and develop a certificate. Select Production> Apple Push Notification service SSL (Production ).

4. Add Devices:

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

 

Enter a device Name.

Enter the UDID of the device you want to add to the test.

Click Next

Click Register.

 

Click Done.

 

5. Find the device's UDID:

Use your iOS device to connect to your computer and open iTunes.

You can see a serial number at the device summary. clicking the serial number will change to a UDID.

 

6. Generate the configuration file

There are also two types of configuration files, one is development, the other is release, the development requires us to do the test, the release is what we need to release on the Appstore, we all need to generate.

Select Provisioning Profiles-> Development and click the plus sign in the upper right corner.

 

Select iOS App Development and click Next.

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

 

Select the certificate of our developer here. If you do not know which one is, select all.

 

Select our test device. If not, add the device in the previous Devices.

 

Just get a name and download it.

 

The release configuration file is created like the Development Configuration File. Select Distribution-> Ad Hoc, which is the same as the release configuration file.

 

 

After the certificate is configured, open the application project we created.

Open the AppDelegate. m file, add the following code in-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions method, and register message push

 

-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {// Override point for customization after application launch. /** message push registration */if ([UIDevice currentDevice]. systemVersion. floatValue> = 8.0) {UIUserNotificationSettings * settings = [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeBadge | uiusernotiftypetypesound | UIUser NotificationTypeAlert categories: nil]; [application registerUserNotificationSettings: settings]; [application registerForRemoteNotifications];} else {[application details :( optional | uiremotenotiftypetypesound | response)];} return YES ;} the following method returns the unique identifier generated by the ANPs Apple push server/** the unique identifier token of the device sent back by the receiving server */-(void) application :( UIApplication *) Application didRegisterForRemoteNotificationsWithDeviceToken :( NSData *) deviceToken {// it takes a long time to obtain the DeviceToken from the first running! // Convert deviceToken into a string so that NSString * token = [deviceToken description]; NSLog (@ "description % @", token );} when a message is pushed back, the following method is triggered when the PUSH message/** device receives a message from the apple push server, used to display the PUSH message */-(void) application :( UIApplication *) application didReceiveRemoteNotification :( NSDictionary *) userInfo {NSLog (@ "userInfo ==%@", userInfo);} when the PUSH Service registration fails, receive error message/** registration PUSH Service failed */-(void) application :( UIApplication *) application didFailToRegisterForRemoteNotificationsWithError :( NSError *) error {NSLog (@ "registration failed % @", error );}

 

 

 

Server (Java Server)

On the server side, we need a certificate with the suffix. p12 and the required jar package.

Server certificate generation method:

Open the certificate we downloaded earlier and find it in the key string

 

Right-click and choose Export

 

To export a file with the suffix. p12 to your computer, you need to enter a password, which is used on the Java Server.

 

Jar packages required by the Java Server

Java server 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 = "allow "; // The iphone application identifier PayLoad payLoad = new PayLoad (); payLoad. addAlert ("test my push messages"); payLoad. addBad Ge (1); payLoad. addSound ("default"); pushicationicationmanager pushManager = PushNotificationManager. getInstance (); pushManager. addDevice ("iphone", deviceToken); // test 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 "; // int port = 2195; String certificatePath = "/Users/hsw/Desktop/PushTest. p12 "; // just now Certificate String certificatePassword = "123456"; pushManager exported in mac system. 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! ");}}

 

 

 

Link: http://blog.tingyun.com/web/article/detail/571

 

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.