iOS remote push, from mechanism to implementation, as detailed as possible

Source: Internet
Author: User
Tags openssl x509

I write a blog for the first time, write bad place everyone please forgive me.

This article mainly refers to the http://blog.csdn.net/showhilllee/article/details/8631734, thanks to Showhilllee detailed explanation. Because in the process of doing some of their own understanding and change, so you write again on the push of the detailed blog.

This article is divided into four parts:

I. EXPLANATION APNS remote PUSH

Second, configure the push certificate

Third, export the certificates that are available to your server

Iv. code implementation Device registration push, get push message

Okay, now we're going to start with a formal push.

First, an old picture, Apple very early to everyone, push the flowchart.

Although iOS updates many versions, this process of pushing has never changed. The push mechanism is: the first time the device application is opened to APNs (Apple push server) registration push, and get device token devicetoken-> app will send Devicetoken to their own push server or third-party push server to save Your own server or a third-party push server sends messages and Devicetoken bundles to the Apns->apns to send messages to the device, and the device displays push messages.

Devicetoken similar UUID, after the application of the first request Devicetoken, if the application does not remove the reinstallation Devicetoken is not changed, the app is removed and then reinstalled, and then registered remote push Devicetoken will change. So each application open should go to register push and request Devicetoken, the first time there will be prompted whether to push, select Push, you will receive the callback function in Devicetoken, the first time there will be some delay, and then open the application request Devicetoken seconds back.

Apple's APNs server is dedicated to push, divided into Test address and official address, all Apple push messages to go through APNs push communicated to the device, regardless of the test or formal. In fact, the principle of push is that the device will get the Devicetoken sent to their own server to save, their own server choose to save the Devicetoken and to push the message package sent to Apns,apns automatically pushed to the specified device. Third-party push in Apple push this is just a step in the middle of their own server and APNs, their servers send messages and device identities to third-party servers, third-party push and then the device to find Devicetoken, send messages to APNs.

Second, configure the push certificate

1. Open the local keychain, the top left corner keychain Access-"certificate assistant-" request a certificate from a certification authority

User e-mail address generally fill in the developer account mailbox, select Storage to disk, save on the desktop, the name does not change.

2, (1) Open the browser, login to Apple Developer, select the top navigation bar account, login

After entering the interface, select Certificates-development click on the upper right corner plus

Select the second option for development, Apple Dev Service certificate Apple Push Notification service SSL (APNs), click Continue

Here we need to choose an app ID, we do not tell where to build, assuming already have a, click Next continue

Click Choose File to select the native generated

Click Continue, download the generated Aps_development.cer file, and save a new push folder on the desktop.

(2) The following is the APP ID new, click Identifiers->app ids-> upper right corner plus

After entering this interface, name is set to the name of your project (optional), bundle ID to match the bundle ID in the project, select Explicit AppID is for the unique certificate, Wildcard app ID is a team certificate, do push without Wildcard app ID , select Explicit AppID.

Under this page, tick push notifications

Click on continues and click Register on this screen.

The next step is to fill out the app ID in the (1) section.

(3) Download. mobileprovision File Click the plus sign in the upper right corner of provisioning profiles-all-.

Because it's a development environment, choose Development's iOS app and publish your environment to choose distribution. Next Choose Appid,cer,devices, which is the "which application, which certificate, which device" logic.

Profile name can be used casually. Download the. mobileprovision file and put it in the new push folder that you just created.

Well, at this point, the certificates are all configured.

Iii. Configuring. P12 files and. pem files required by Windows Server

The. p12 file is a verification certificate required by the server push, and if you need to push it with a third party, you should first tell me how to generate the file.

1. First, double-click Install the. cer and. mobileprovision files that were generated in the previous section.

Open the keychain and locate the. cer certificate that you just installed, click-Right-"Export" * * * * * *, pop up this window

Name casually, in order to prevent accidental not in Chinese, save to just the new push folder, click on the storage pop up this window

This is the. p12 file needs to set an access password, enter the password, simple point on 123456, verify that the input again just entered 123456, click OK.

If you use a third-party push that export. p12 file is enough.

2. If you are building a push server or windows, you will need the. pem file, and we'll convert the. cer file and the newly generated. p12 file to a. pem file, respectively.

Open the terminal, type the CD and enter the path of the push folder into the Push folder

After you can tap the CD space, locate the push folder in the Finder, and press and hold the Blue folder icon of the circle push to drag it into the terminal to display the path directly.

(1) Enter command after entering the push folder: OpenSSL x509-in aps_development.cer-inform der-out Pushchatcert1.pem

This directive means that the downloaded Aps_development.cer certificate file is generated by the. Pem file called PushChatCert1, which is the. PEM filename, but you want to indicate that this is a. cer file conversion generation.

(2) Re-enter the command: OpenSSL pkcs12-nocerts-out pushchatkey.pem-in sharepush.p12, enter the P12 password and set the PEM password, in order to facilitate the installation of the same. This directive is to generate. pem files from the. p12 file, Pushechatkey.pem's name is random, ditto, and know that this is a. p12 file.

After entering the command, you need to enter the. P12 password, enter the password to set this. pem file for easy setup and the same password as. p12 file 123456

(3) synthesize a. pem file with the two. Pem files you just generated, instructions: Cat Pushchatcert1.pem Pushchatkey.pem > Ck.pem

Synthesizing a new. Pem file is called CK, which is a casual, self-remembering on the line.

(4) Next Test These two files connect Apple Test push server

Enter the test Connection directive: Telnet gateway.sandbox.push.apple.com 2195. Control+c Broken Connection

Enter the test notification directive: Notify OpenSSL S_client-connect Gateway.sandbox.push.apple.com:2195-cert pushchatcert1.pem-key PushChatKey.pem. Enter any character to cut off the connection

OK, so the environment and the certificate are all configured. Start tapping the code below.

Four, open Xcode, create a new project, this will not say, open the APPDELEGATE.M file

(1) in

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchoptions function Enter the following code to want to APNs registration push, the first line of code means that when the app opens, the app icon in the upper right corner of the message is empty.

The reason behind judging the device system version is that the function of the push notification has changed since iOS8.0.

 [[uiapplication sharedapplication] Setapplicationiconbadgenumber:0  Span style= "color: #000000;"    >];  if  ([[[Uidevice Currentdevice] systemversion] Floatvalue]>=8.0   | Uiusernotificationtypealert |         Uiusernotificationtypebadge) Categories:nil];    [[UIApplication sharedapplication] registerforremotenotifications];  else  {[[UIApplication Sharedapplication] Registerforremotenotificationtypes:uiremotenotificationtypebadge  | Uiremotenotificationtypealert|    uiremotenotificationtypealert]; } 

-(void ) Application: (UIApplication *) application Didregisterforremotenotificationswithdevicetoken: (nsdata *) devicetoken{ Span style= "color: #008000;" >//  here handle Devicetoken, save your own server for Devicetoken or bundle it with other information } 
-(void ) Application: (UIApplication *) application Didreceiveremotenotification: (nsdictionary *) userinfo{ //     NSLog (@ "userinfo:%@", userinfo);  //  NSLog (@ "received push message:%@", [[UserInfo    objectforkey:@ "APS"] objectforkey:@ "alert"]);  NSString *message = [nsstring stringwithformat:@ "  , [[UserInfo objectforkey:@"  aps  ]objectforkey:@"  alert   ]];}  
-(void) Application: (UIApplication *) app Didfailtoregisterforremotenotificationswitherror: (Nserror *) Err {        @ "Error:%@", err];    NSLog (@ " Get token failed:  %@", str);    }

The function of Didregisterforremotenotificationswithdevicetoken is to return Devicetoken after successful registration.

Didreceiveremotenotification This function is to get to the push message callback, the parameter userInfo is the message body, the type is the word typical, through [[UserInfo objectforkey:@ "APS"] objectforkey:@ "alert") is preferable to the specific message content.

Didfailtoregisterforremotenotificationswitherror This function is useful if the registration push fails the callback, you can do some processing.

This project also wrote the push code, the following simple write a php file, when the server to Apple push communicated a push, Devicetoken just after the project was executed after the Devicetoken received.

Five, PHP code

<?PHP// ?????????? Devicetoken???????????????$deviceToken ='write here to get to the Devicetoken';//Put your private key ' s passphrase here:$passphrase ='here to write the password of the Pem file before setting';//Put your alert message here:$message ='push test: Hellow world!';////////////////////////////////////////////////////////////////////////////////$ctx=stream_context_create (); Stream_context_set_option ($ctx,'SSL','Local_cert','here Write a PEM file name that was synthesized before two PEM files'); Stream_context_set_option ($ctx,'SSL','Passphrase', $passphrase);//Open A connection to the APNS server//?????????? //$fp = stream_socket_client (? SSL://gateway.push.apple.com:2195, $err, $errstr ,//Stream_client_connect, $ctx);//????????????? AppStore??????$FP =Stream_socket_client ('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, -, stream_client_connect|stream_client_persistent, $ctx);if(!$fp) Exit ("Failed to connect: $err $errstr" . PHP_EOL); Echo'Connected to APNS' . Php_eol;//Create the payload body$body ['APS'] =Array ('Alert'=$message,'badge'=1,' Sound'='default');//Encode the payload as JSON$payload =Json_encode ($body);//Build the binary notification$msg = Chr (0) . Pack'N', +) . Pack'h*', $deviceToken). Pack'N', strlen ($payload)). $payload;//Send It to the server$result =fwrite ($fp, $msg, strlen ($msg));if(!$result) echo'Message Not delivered' . Php_eol;ElseEcho'Message successfully delivered' . Php_eol;//Close The connection to the serverfclose ($fp);?>

Save the PHP file in the previously mentioned push folder, the name is called push.php.

Open the terminal, enter the Push folder, enter the command: PHP push.php, enter the execution.

Well, finally finished, the first time to write a blog too laborious, before saving the draft before opening the draft no picture, the picture has to be re-cut, and wrote half on the browser ' dead ', or re-write ... Well, just think of a way, first cut all the pictures, and then write a blog, so fortunately. In short, the writing is not good place everyone light spray AH ~

iOS remote push, from mechanism to implementation, as detailed as possible

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.