Step-by-step implementation of the iOS app push feature

Source: Internet
Author: User
Tags pkcs12 ssl certificate

1. Push principle

IOS push working mechanism can be summarized in brief

    • Provider: Application of its own server;
    • APNS: Apple push Notification service abbreviation, Apple's push server;

The main work flow for push is:

    • After the iOS device connects to the network, it will automatically keep a long link like TCP with APNs, waiting for APNS push message to arrive;
    • The app is registered to the application server (i.e. provider) by registering the message push at startup and acquiring the device's unique device Devicetoken registered in APNs.
    • When a push message is needed for an app, provider packages the push content, the Devicetoken that receives the push message, in the format specified by APNs, and sends it to APNS;
    • APNs receives the message sent by provider, looks for the device that Devicetoken specified, pushes the message to the device if it has established a connection with APNs, and pushes the message to the device the next time the device is connected to APNs if the device is not in line. Please note that Apple does not guarantee that the push will be successful;
    • After the device receives the push message, the IOS system will determine that the push message is sent to the application based on the SSL certificate, and the client is started.

In the above process, there are two key steps that need to be dealt with yourself: 1. The client obtains the Devicetoken and uploads the Provider;2.provider to send the push message to APNs. Apple's push certificate authorization is required in both steps, and the following describes how to generate the push certificate, as well as the provisioning profile.

2. Push certificate and Provisioning profile generation
  • Sign in to http://developer.apple.com/iphone/index.action with a paid account

  • Generate a development certificate before you generate a push certificate

    The process of generating a development certificate is not described in detail, and you can refer to how to debug and publish the program online. Just one thing to be aware of, the generation of the development certificate process needs to generate a CSR file through keychain, the default name is Certificatesigningrequest.certsigningrequest, this file will be used when generating the push certificate.

  • Create an app ID

    • During the creation process, description can be filled in arbitrarily, such as called push_demo ;
    • Bundle identifier generally in com.company.appname such a format, for example com.mycompany.demo ;

    Note: To use the push function bundle identifier must not appear wildcard characters, for example com.mycompany.* , such names can not use push.

  • Generate Push SSL Certificate

    After generating the app ID, click on the Configure configuration page. Open the Enable for Apple Push Notification service option, under which there are Development Push SSL Certificate and Production Push SSL Certificate two SSL certificate can be configured, the previous one is used for the development of the push certificate, and the latter one is for publishing. We take the development of the push certificate as an example, click Development Push SSL Certificate -To, followed by a request to select a Configure CSR file, This is the Certificatesigningrequest.certsigningrequest file when the development certificate is generated, and after choosing a good CSR, the corresponding SSL certificate is generated. Download down and save the name as aps_developer.cer .

  • Export the private key from keychain, set a good password, and name it PRIVATE_KEY.P12

  • Generate a push certificate

    • Then we got 3 files altogether:

      1. Certificatesigningrequest.certsigningrequest
      2. Private_key.p12
      3. Aps_developer.cer
    • Turn Aps_developer.cer into PEM format

    • Convert the private key in the PRIVATE_KEY.P12 format to Private_key.pem

      openssl pkcs12 -nocerts -out private_key.pem -in private_key.p12

      This step requires you to enter the password for the P12 private key, and to set the password for the newly generated PEM.

    • Creates an SSL P12 format certificate for the server, named Aps_developer.p12

        OpenSSL pkcs12-export-in Aps_developer.pem-inkey Private_key.pem-certfile certificatesigningrequest.certsigningrequest-name "Aps_developer"-out aps_developer.p12< /code> 

      This step will require you to enter a PRIVATE_KEY.PEM password, note that it is not a private_key.p12 password. If the password is incorrect, or if the Certificatesigningrequest.certsigningrequest file does not match, the Aps_developer.p12 file cannot be generated properly if the generated Aps_ The developer.p12 file size is 0, indicating that there was a problem during the build process, check that the PEM private key, password, and certificatesigningrequest.certsigningrequest are correct.

      Aps_developer.p12 is the SSL certificate provider needs to send the push message to APNs. With this certificate and password to the server, the server can send a push message to APNs. At this point the server is ready to work, but the client must also configure the appropriate provisioning profile to start the app's push feature.

      Server configuration It is important to note that since we are generating a push certificate for the development environment, the server should connect to the APNs sandbox address: gateway.sandbox.push.apple.com:2195 , if the application is officially released, it is necessary to connect to the formal environment, you must generate the appropriate publishing certificate, and connect the APNS formal environment address: gateway.push.apple.com:2195 .

  • Generate Provisioning Profile

    • New profile, named Push_dev;
    • Select the appropriate certificate;
    • APP ID Select Push_demo;
    • Select equipment;
    • Download and install the profile for development use;
3. Xcode certificate settings, info.plist settings
    • Open the client project with Xcode and set the info.plist bundle identifier as com.mycompany.demo .
    • To open the project settings, the certificate must be set to the certificate associated with Push_dev.
4. Client Access Devicetoken

The server must also know the Devicetoken of the device to send a push message to a device. After the app is run, get to the Devicetoken, and then to the server, the following describes how the app gets Devicetoken. The app must first register to use the push feature.

  -(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {      [[UIApplication Sharedapplication] registerforremotenotificationtypes: (Uiremotenotificationtypealert | Uiremotenotificationtypesound | Uiremotenotificationtypebadge)];      Do something      //...  }

Add the following method in Appdelegate to get the Devicetoken:

-(void) Application: (UIApplication *) app Didregisterforremotenotificationswithdevicetoken: (NSData *) DeviceToken {      nsstring *token = [NSString stringwithformat:@ "%@", Devicetoken];      NSLog (@ "%@", token);  }  -(void) Application: (UIApplication *) app Didfailtoregisterforremotenotificationswitherror: (Nserror *) Error {      NSLog (@ "%@", error);  }

After the application gets to the Devicetoken, the Provider,provider can use this devicetoken to give the device push message.

5. Payload format and custom data

After the server has configured the certificate and gets the Devicetoken, it can send a message to APNs. The format for sending messages is as follows:

Payload is the message payload of push, which is the data that the application needs to be concerned about. Payload is a JSON dictionary with a maximum value of 256 bytes, exceeding this limit, APNs will refuse to forward. The basic format is as follows:

{"    APs": {      "alert": "Hello push!",      "badge": 1,      "sound": "Default"    },    "page": "Home"  }

Must contain a aps key value. badgerepresents the number displayed by the application icon, sound indicating that the beep of the push was received. Payload specific structure refer to Apple Push Notification Service

To add custom data to this structure, add it outside of the APS space. For example, a background push message to the app also requires the app to open a page:

The background tells the client to open the app's homepage after receiving the push, and the page and home are defined by themselves. It is important to note that the payload size cannot exceed the limit, so you can simplify the custom data point, such as the home with the number 1, page shorthand for p, so that "p":1 the opening of the home page, you can reduce the size of payload.

6. Client receives push message

After the iOS system receives the push message, if the user clicks View, the system launches the app according to the certificate. If the app has started, the Appdelegate method will be called:

  -(void) Application: (UIApplication *) application didreceiveremotenotification: (Nsdictionary *) UserInfo {      // UserInfo is the payload of the push message  }

If the app has not started yet, it can still get payload after booting through push cold boot:

  -(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {      nsdictionary* userInfo = [Launchoptions Objectforkey:uiapplicationlaunchoptionsremotenotificationkey];      NSLog (@ "Payload:%@", userInfo);  }

So far, the push function is basically complete, you can start the push function test, if the server has not been developed, or if you want to quickly test whether the normal push, you can use the following code to implement background push test. Configure the SSL certificate and the Devicetoken and payload structures before sending the push.

Object C version
Version C
Java version
PHP version

There is a small problem, when payload set the badge, the app icon will always display a number hint, if you want to clear the number hint, or set to another number, call the following function to complete.


[[UIApplication sharedapplication] setapplicationiconbadgenumber:number];

A number of 0 clears the numeric hint.

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.