The remote push principle and process _ios of IOS

Source: Internet
Author: User
Tags unique id


Push notifications are now an essential feature of the application. So how do we implement remote push in IOS? What is the remote push principle of IOS? When doing IOS remote push, we have all kinds of problems. So first let's prepare something to do the push. We need a paid Apple developer account (no remote push is free), and with a developer account, we can go to the Apple Developer website and configure the required push certificate. Then download the certificate for us to use later, the detailed certificate configuration process, we say below.



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



Apple's push service notification was done by its own dedicated push server APNs (Apple push Notification service), which was APNs received a push message from our own application server and pushed the message to the specified IOS device. The iOS device is then notified to our application, and we will receive a push back message in the form of a notification or sound. The premise of the iOS remote push is that the iOS device with our application needs to be registered to the APNS server and the APNS server will return a devicetoken after we get to the token and send this token to our own application server. When we need to push the message, our application server packs the message in the specified format and then sends it to the APNS server together with the IOS device's devicetoken. Our application maintains a long TCP based connection with the APNs server, and the APNS server pushes the new message onto the iOS device and then displays the push message on the device screen.



Flowchart of Device registration APNs :






The diagram above completes the following steps:



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



2. The connection is successful, APNs is packaged and processed to produce devicetoken and returned to the registered device (equipment)



3.Device (equipment) carry acquired devicetoken send to our own application server



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



Push process diagram:






The push process is followed by the following steps :



1. First of all, our equipment has a push to install the application (the application will be registered with the code message Drive), our iOS devices in the case of a network will be connected to the APNs push server, the connection process, the APNS server will verify the Devicetoken, the successful connection to maintain a TCP The long connection;



2.Provider (our own application server) receives the message which needs to be pushed and packages it to the APNS server together with the Devicetoken of the iOS device being pushed;



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



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



A more intuitive flowchart:






Information Package Structure diagram:






The message body shown above is the message structure that our application server (Provider) sends to the APNS server, APNs Verify that the structure is correct and extract the information, and then push the message to the specified iOS device. This structure consists of five parts, the first part is the command designator, 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), and the final part is the true message content. , which contains the basic information of the push message, such as the content of the message, how many digits are displayed in the top right corner of the icon and the sound that is played when the push message arrives.



Structure of Payload (message body):


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


This is actually a JSON structure, alert label content is to be displayed on the user's mobile phone, the number of badge display (note is integral type) will be in the application icon in the upper right corner of the number of display, prompted how many unread messages, sound is when push information delivery is the voice of mobile phone play , the Defalut is marked with the system default sound.



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



1. First, we want to create a new certificate signing request (that is, CSR) requests file



Find Keychain Access in the Use tool in your application and choose to request a certificate from a 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, here I selected is my folder), click on storage



Then we'll see a certificatesigningrequest.certsigningrequest request file in Tingyun when we click on it, which is the CSR file we're talking about. When we generate the CSR file, we will generate a pair of secret keys in the keychain access, named after the common name we just filled out.



2. Configure AppID



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



Click Account






Select Certificates,identifiers&profiles






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






Name: Just fill in the App name.



App ID Suffix and Explicit app ID with no wildcard characters selected



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






Choose the service you need in the APP services below



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



Then click Continue






3. Create a certificate



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



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






Select Apple Push Notification service SSL (Sandbox), Create push service certificate Click Next






The app ID here selects the app ID we just created



Then click Next and Next






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



Then click Generate (Generate)



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






Publish the 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 "+" number in the upper left corner.






Name to fill in a device name.



UDID fill in the UDID of the equipment that you need to join the test.



Then click Next






Then click Register to






Click Done.









5. Find the UDID of the equipment:



Connect to your computer with your IOS device and turn on ITunes.



In the device summary can see a serial number, click the serial number will become UDID.






6. Generate Configuration file



There are also two types of profiles, one that is developed, one that is released, which is developed to make testing necessary, what we need to publish on the App Store, and we need to generate.



Our husband into the development profile, select provisioning Profiles->development click on the top right corner of the + number.






Choose iOS App Development click Next






The app ID here still chooses the app ID we just created.









Here select our Developer's certificate, if you do not know which choice is all






Choose our test equipment here, if not, add it in front of the devices









Just grab a name and download it.






The publish profile is created like the development profile, and you can select Distribution->ad, followed by the release profile.












Certificate configuration complete, open the application project we created



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


- (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (launchOptions NSDictionary *) {
// Override point for customization after application launch.
/** message push registration */
If ([UIDevice currentDevice]. SystemVersion. FloatValue > = 8.0) {

UIUserNotificationSettings * 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 id generated by the ANPs apple push server
/** the unique identity of the device returned by the receiving server is token */
- (void) application: (UIApplication *) application didRegisterForRemoteNotificationsWithDeviceToken: (deviceToken NSData *) {

// it takes a long time to get DeviceToken on the first run!
// converts deviceToken to a string for later use
NSString *token = [deviceToken description];
NSLog (@ % @ "description", token);
}

The following method is to receive a push message when one comes back
/ * * triggered when the device receives a message from the apple push server to display the push message * /

- (void) application: (UIApplication *) application didReceiveRemoteNotification: (the userInfo NSDictionary *) {

NSLog (@ "the userInfo = = % @", the userInfo);
}

The above method is to receive an error message when the registration of the push service fails
/** failed to register the push service */
- (void) application: (UIApplication *) application didFailToRegisterForRemoteNotificationsWithError error: (NSError *) {
NSLog(@" registration failed %@",error);
}



Server side (Java server)



Server side We need, a suffix for. P12 's certificate, and the required Jar pack



Server-Side Certificate generation method:



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






Click the right mouse button to select Export






Export A. p12 file to your computer, and you need to enter a password that you want to use on the Java server side






Java server-side Jar packages required






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 = ' eab6df47eb4f81
    E0aaa93bb208cffd7dc3884fd346ea0743fcf93288018cfcb6 ";
    Pushed iphone application designator PayLoad PayLoad = new PayLoad ();
    Payload.addalert ("Test my Push Message");
    Payload.addbadge (1);
      
    Payload.addsound ("Default");
    Pushnotificationmanager 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.s Andbox.push.apple.com ";
    Test Apple push Server int port = 2195; String Certificatepath = "/USERS/HSW/DESKTOP/PUSHTEST/PUSHTEST.P12";
   
    Certificate String certificatepassword= "123456" that was exported under the Mac system just now; 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!");
 }

}


This article has been organized into the "iOS push Tutorial", welcome to learn to read.



The above is the complete iOS remote push principle and the realization process, hoped that is helpful to everybody's study.


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.