[IOS development] IOS development push and ios development push

Source: Internet
Author: User
Tags key string openssl x509 what openssl ssl certificate

[IOS development] IOS development push and ios development push

The push was used in recent projects. The first push encountered many pitfalls and was recorded.


Reference: Teach you how to push IOS


First, some basic knowledge

Push mechanism of APNS

First, let's take a look at Apple's official explanation of the iOS push mechanism. For example

Provider is the background server of our own program. APNS is the abbreviation of Apple Push Notification Service, that is, Apple's Push server.

 

There are three phases:

Stage 1: The Application Server packs the message to be sent and the ID of the target iPhone and sends it to APNS.

Stage 2: APNS searches for the iPhone with the corresponding identifier in its registered Push Service iPhone list and sends the message to the iPhone.

Stage 3: The iPhone transmits the sent message to the corresponding application, and a Push notification is displayed according to the settings.

 

Detailed workflow of APNS push notifications

The following figure shows the detailed workflow of APNS push notifications:


 


Based on the picture, we can summarize:

 

1. The application registers for APNS message push.

2. iOS obtains the devicetoken from the APNS Server, and the application receives the device token.

3. The application sends the device token to the PUSH server program of the program.

4. The server program sends a message to the APNS service.

5. The APNS Service sends messages to the iPhone application.



Okay. Let's talk about the process.Preparations

1. an iphone. Ipod or ipad

2. developer account

3. IOS development environment



Next, the official start.


1. Create a project

Remember that our Bundle Identifier is com. slpcb. PushDemo.



Ii. Create a certificate

Certificates are required between our clients and Apple servers and between our own servers and Apple servers. Next we will start the certificate creation process.


1. Generate the CSR File

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

Open the access key string, click access key string-certificate assistant-request a certificate from the Certificate Authority




2. Create a certificate

EnterApple developer website,


Add a new APPID


Enter necessary information


Note that you must enter a specific appid, which cannot be used for wildcard configuration.



Select push notification, and click Continue



Next, submit


Next we will go back to the APPID list, edit the just-produced APPID, and click "create certificate ".

Confirm step by step

Select the CSR File Created in step 1.



Select and confirm




Then download the certificate (remember to download and double-click to install)






3. Generate Profile

After the certificate is created, we need the corresponding Profile file.

As shown in the preceding figure, go to the Management page and click Add.


Continue




Current App ID, continue



Select a certificate and continue



Select a device and continue




Start a name and continue



Okay, it's done. download it.






After the certificate is created, process it.


First, export the certificate.


Open the key string and right-click to export the certificate we just generated




Name




Set the password, which is very important. Remember. Here I set it to 123456





Now let's take a look at the above steps. We have obtained the following files:

1. PushDemoDev. certSigningRequest CSR File

2. aps_development.cer SSL Certificate file

3. PushDemo. p12 key file



But this is not enough. What we need is to generate a file with the suffix pem. Next we will fix it.



Open the terminal and locate the location of our files



1. Convert the. cer SSL Certificate to the. pem file and run the following command:

Openssl x509-in aps_development.cer-inform der-out PushChatCert. pem

A PushChatCert. pem file is generated in the push and organize folder.


2. Convert the private key PushDemo. p12 to the. pem file:

Openssl pkcs12-nocerts-out PushChatKey. pem-in PushDemo. p12

Here, you will be asked to enter the password three times. The first time you set the password for the p12 file everywhere, that is, the 123456 password we set above.

The second and third time is to set a password for the pem file we generated. This password needs to be told to the server. For convenience, we set it to 123456



3. Generate the two pem files into a pem file to integrate the certificate and private key into one file:

Cat PushChatCert. pem PushChatKey. pem> ck. pem
Generate the ck. pem File



Next we will use the generated SSL Certificate and private key to set a secure link to the Apple Server:

Openssl s_client-connect gateway.sandbox.push.apple.com: 2195-cert PushChatCert. pem-key PushChatKey. pem

After executing this command, we need to enter the secret

Enter pass phrase for PushChatKey. pem:

Enter 123456 and press Enter.

You will see a complete output, let you understand what OpenSSL is doing in the background. If the link is successful, you can enter a single character and press enter to disconnect the server. If there is a problem with the connection, OpenSSL will return an error message.


If you see the following feedback, it means you have succeeded.






Now, let's look at the project we created at the beginning.



Open the project PushDemo

Open AppDelegate

Change

-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions

{


// Push form: Tag, sound, and prompt

[[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | uiremotenotiftypetypesound | UIRemoteNotificationTypeAlert];

Return YES;

}


-(Void) application :( UIApplication *) application didRegisterForRemoteNotificationsWithDeviceToken :( NSData *) pToken {

NSLog (@ "regisger success: % @", pToken );

// Register successfully. Save the deviceToken to the Application Server database.

}

-(Void) application :( UIApplication *) application didReceiveRemoteNotification :( NSDictionary *) userInfo {

// Process push messages

NSLog (@ "userinfo: % @", userInfo );

NSLog (@ "received push message: % @", [[userInfo objectForKey: @ "aps"] objectForKey: @ "alert"]);

}

-(Void) application :( UIApplication *) application didFailToRegisterForRemoteNotificationsWithError :( NSError *) error {

NSLog (@ "Registfail % @", error );

}




Then set








Run one. After the notification is successfully received, the application will pop up to allow the user to confirm receipt of the notification.



At this time, let's take a look at xcode output, which outputs the deviceToken of our apple machine and writes it down.




Click.



The next step is our server debut.

PushMe. php

The Code is as follows:


Note that

Change the value of $ deviceToken to the deviceToken we obtained above, and remove the space.

$ Passphrase is the password we set earlier, 123456



<? Php


// Put your device token here (without spaces ):

$ DeviceToken = '978042ec5cda4a0e790b14431d00e33218c9707526d3ac3cf0d8549b72cef2cd ';


// Put your private key's passphrase here: secret language

$ Passphrase = '20140901 ';


// Put your alert message here:

$ Message = 'Publish test! "';


//////////////////////////////////////// ////////////////////////////////////////


$ Ctx = stream_context_create ();

Stream_context_set_option ($ ctx, 'ssl ', 'local _ cert', 'ck. pem ');

Stream_context_set_option ($ ctx, 'ssl ', 'passphrase', $ passphrase );


// Open a connection to the APNS server

$ Fp = stream_socket_client (

'Ssl: // gateway.sandbox.push.apple.com: 8080', $ err,

$ Errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ ctx );


If (! $ Fp)

Exit ("Failed to connect: $ err $ errstr". PHP_EOL );


Echo 'connectedto apns'. PHP_EOL;


// Create the payload body

$ Body ['aps '] = array (

'Alert '=> $ message,

'Sound' => 'default'

);


// Encode the payload as JSON

$ Payload = json_encode ($ body );


// Build the binary notification

$ Msg = chr (0 ). pack ('n', 32 ). 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;

Else

Echo 'message successfully delivered'. PHP_EOL;


// Close the connection to the server

Fclose ($ fp );

?>






Put pushMe. php In the certificate directory, and then locate the directory on the terminal.

Run: php pushMe. php





Yeah, I'm done!


However, this is only a development version. If you want to release the version, you need to create the corresponding release version certificate. Of course, the address also needs to change.


APNS address
Test addressGateway.sandbox.push.apple.com: 2195
Release addressGateway.push.apple.com: 2195

The address used for the test is sandbox, and the publishing address is different. Remember to change it when releasing the software.









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.