Step-by-step implementation of iOS application push function

Source: Internet
Author: User
Tags openssl pkcs12 ssl certificate

Original from: http://tanqisen.github.io/blog/2013/02/27/ios-push-apns/

1. Push principle

the IOS push working mechanism can be summarized in the following diagram

Provider: Apply your own server; apns:apple push Notification service, Apple push server;

the main work flow of the push is: after the iOS device is connected to the network, it will automatically keep a long link with apns like TCP, waiting for the arrival of the APNS push message; Register message push when application starts, And get the device's unique device identifier registered in APNs Devicetoken to the application server (i.e. provider), and provider push content, The devicetoken that receives the push message is packaged in the format specified by APNs, sent to APNs, and APNs receives the message sent by provider to find the device specified by Devicetoken, if the device has already established a connection with APNs, The message is immediately pushed to the device, and if the device is not on line, the message is pushed to the device the next time the device is connected to APNs. Please note that Apple does not guarantee that the push will be successful; After the device receives a push message, the iOS system determines that the push message is sent to the application based on the SSL certificate, thereby initiating the corresponding client.

In the above process, there are two key steps that need to be handled by themselves: 1. The client gets the Devicetoken and uploads the push message to the APNs Provider;2.provider. Both of these steps require Apple's push certificate authorization, and here's how to generate a push certificate and provisioning profile. 2. Push certificate and Provisioning profile generation

log in to http://developer.apple.com/iphone/index.action with a paid account

build 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 note, the process of generating a development certificate involves generating a CSR file by keychain, with the default name Certificatesigningrequest.certsigningrequest, which will be used when generating a push certificate.

Create an app ID creation process description can be arbitrarily filled out, such as Push_demo; Bundle Identifier generally in such a format as com.company.appname, such as Com.mycompany.demo;

Note: To use the push function of the bundle identifier must not appear wildcard characters, such as com.mycompany.*, such a name can not use the push.

Generate push SSL certificate

After generating the app ID, click Configure to enter the configuration page. Open the Enable for Apple push Notification service option, which has development push SSL certificate and production push SSL certificate two SSL Certificate can be configured, the front one is used for the development of the push certificate, the latter one is used for publishing. For example, to develop a push certificate, click Development Push SSL certificate->configure, and then ask for a CSR file, This is the Certificatesigningrequest.certsigningrequest file that generates the development certificate, and then the corresponding SSL certificate is generated when the CSR is selected. Download and save the name Aps_developer.cer.

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

generate a push certificate

Then we got 3 files: certificatesigningrequest.certsigningrequest private_key.p12 aps_developer.cer

Converting Aps_developer.cer to PEM format


Converts the private key in 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 a password for the P12 private key, and to set the password for the newly generated PEM.

Create the SSL P12 format certificate for the service side, 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

This step will require you to enter a PRIVATE_KEY.PEM password and 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 will not be generated correctly if the generated Aps_ The developer.p12 file size is 0, which indicates a problem during the build process, check the PEM private key, password, and certificatesigningrequest.certsigningrequest whether it is correct.

APS_DEVELOPER.P12 is the SSL certificate that provider sends a push message to APNs. With this certificate and password provided to the server, the server can send a push message to APNs. At this point, the server can already work, but the client must also configure the appropriate provisioning profile to start the application push function.

Server configuration Note that as we generate a push certificate for the development environment, the server should connect to the APNS sandbox environment address: gateway.sandbox.push.apple.com:2195, if the application is officially released, it is necessary to connect the formal environment , you must generate a corresponding publishing certificate and connect to the APNS official 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 the device; Download and install the profile for development use; 3. Xcode certificate settings, info.plist settings with Xcode Open Client project, set Info.plist bundle identifier for Com.mycompany.demo. To open the project settings, you must set the certificate to the certificate associated with the 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 application runs to Devicetoken and then to the server, the following describes how the application obtains Devicetoken. Applications must be registered to use the push function first.

  -(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {
      [[UIApplication Sharedapplication] registerforremotenotificationtypes: (Uiremotenotificationtypealert | Uiremotenotificationtypesound | Uiremotenotificationtypebadge)];
      Do something
      //...
  }
Add the following method to the 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 be used to push the message to the device using this devicetoken. 5. Payload format and custom data

The server configures the certificate and gets the Devicetoken to send the message to APNs. The format for sending messages is shown in the following illustration:

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

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

Must contain the APS key value. Badge represents the number displayed by the application icon, and sound indicates that a push beep is received. Payload specific structure reference Apple Push Notification Service

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

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

Background tells the client to receive this push to open the application of the homepage, where the page, home are their own definition. It should be noted that the payload size cannot exceed the limit, so you can simplify the custom data point, for example, you can put home with number 1, page is P, so "P": 1 means to open the main page, you can reduce the size of the payload. 6. Client receives push message

After the iOS system receives the push message, if the user clicks on the view, the system will start the application according to the certificate. If the application is started, the Appdelegate method is invoked:

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

If the application has not been started, after the push cold boot, can still get payload after boot:

1
2
3
4
5
  -(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 completed, or want to quickly test whether the normal push, you can use the following code to implement the background push test. Configure SSL certificates and Devicetoken and payload structures before sending the push.

Object C version
C version
Java version
PHP version

There is a small problem, when the payload set the badge, the application icon will always display a number of prompts, if you want to clear the number prompts, or set to other numbers, call the following function can be completed.

1
2
  [[UIApplication sharedapplication] setapplicationiconbadgenumber:number];

Number 0 clears the digit prompt.


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.