IOS PUSH Practice Actions ~ ~ ~

Source: Internet
Author: User

1. Introduction to the push process

       (1) Use the Uiapplication::registerforremotenotificationtypes function to communicate with Apple's APNs server during the app startup process. Make a request to register for a remote push. If the registration succeeds, the callback function application: (uiapplication *) application Didregisterforremotenotificationswithdevicetoken: (NSData *) Devicetoken will be triggered, the app can get Devicetoken, the token is a device-related string .      (2) After the app gets to Devicetoken, Send the Devicetoken to its own server.       (3) After the server gets Devicetoken, use the certificate file to initiate an SSL connection to Apple's APNs servers. After the connection is successful, send a JSON string containing the type and content of the push message.     (4) After the APNS server gets the JSON string, it sends a notification message to the app, making the app's callback function application: (uiapplication *) application Didreceiveremotenotification: (Nsdictionary *) UserInfo is called, the app can get the content of the push message from the UserInfo.    2. Certificate file used and the build process      (1) certsigningrequest file, which is generated on the Mac system, is used to request a push certificate file on the Apple website.           build process:          Open the Keychain Access software in the application, select Keychain Access-"certificate Assistant" from the menu-" To request a certificate from a certification authority, fill out the mailbox and name, and then select Save to disk, you can generate a certificatesigningrequest.certsigningrequest file locally.      (2) register an app ID that supports push, which is used later.         Build process:        Enter developer.apple.com, select Member Center-certificates, Identifiers &A mp Profiles  - identifiers-app IDs, then choose to register the app ID, set the AppID name, and the app ID suffix column must select the explicit app ID, and then set the bundle ID, Finally, check the push notifications in APP services so you can register a aphid that supports push.        (3) The push certificate CER file, which is generated in developer.apple.com to generate the files required by the server.         build process:        Enter developer.apple.com, select Member Center-certificates, identif Iers & Profiles  - certificates, then select Create certificate, type divided into development and product. Take development For example, select Apple Push Notification service SSL (Sandbox), then next, select the previously generated support Push AppID, and then next, submit the CSR file that you created earlier, The next step is to generate a CER file and save it locally.    (4) Generate the certificate file used by the service side. If you are using the Mac version of the Pushmebaby tool on the Internet to send push messages on Mac machines, then the CER file above will suffice. If you are using PHP and java/c# to develop your own server, you will also need to convert the CER file above to generate a PEM file or a p12 file.          generate PHP with PEM file process for:        first double-click on the previously saved CER file, this will open the Keychain access software, there will be apple Development  ios Push Services certificate, a public key and a private key, the name of the key is the same as the name that is filled in in the certificate assistant.       Check certificate, export as APNS-DEV-CERT.P12 file       Check private key, export to APNS-DEV-KEY.P12 file       Over terminal commands convert these files to PEM format:      OpenSSL pkcs12-clcerts-nokeys-out apns-dev-cert.pem-in apns-dev-cert.p12& nbsp     OpenSSL pkcs12-nocerts-out apns-dev-key.pem-in apns-dev-key.p12      Finally, you need to combine two PEM files into one AP Ns-dev.pem file, this file needs to be connected to APNs using:      cat Apns-dev-cert.pem Apns-dev-key-noenc.pem > Apns-dev.pem         (5) generates the provisioning file used by Xcode, which is used for real-machine debugging.           build process:          Enter developer.apple.com, select Member Center-certific Ates, Identifiers & Profiles  - provisioning Profiles, then select Create Provisioning  file, then select iOS App Development, Next select AppID, select the previously established support push AppID, next select the certificate that supports push, next tick the device ID you need to support, The final step is to set the file name of the provisioning file so that the provisioning file is generated.       3. Server development       (1) If you just want to test the push of a message on a Mac computer, you can use the Pushmebaby tool to make it easier to use. The tool is open source, can be from Https://github.com/stefanhafeneger/PushMeBaby, the execution of the code is actually set up the SSL certificate, then connect APNs, and then send the JSON data. Because the SSL logic is being processed, the code is slightly more points. When using a tool, replace the CER file in your project resource with your own CER file, and then replace the Devicetoken in your code with the Devicetoken of your own device.    ///////////////////////////

-(void) application: (uiapplication *) application Didregisterforremotenotificationswithdevicetoken: ( NSData *) Devicetoken

{

nsstring* dt = [[devicetoken description] stringbytrimmingcharactersinset: [nscharacterset Charactersetwithcharactersinstring:@ "<>"];

NSLog(@ "devicetoken:%@", DT);

}

-(void) application: (uiapplication *) application Didfailtoregisterforremotenotificationswitherror: ( Nserror *) Error {

NSLog(@ "did Fail to Register for Remote notifications with error:%@", error);

}

-(void) application: (uiapplication *) application didreceiveremotenotification: (nsdictionary *) userInfo

{

NSLog(@ "didreceiveremotenotification~~~~");

NSLog(@ "Remote notification:%@", [userInfo description]);

nsstring* alertstr = nil;

nsdictionary *apsinfo = [UserInfo objectforkey:@ "APS"];

nsobject *alert = [Apsinfo objectforkey:@ "alert"];

if ([Alert iskindofclass:[nsstring class])

{

Alertstr = (nsstring*) alert;

}

Else if ([Alert iskindofclass:[nsdictionary class])

{

nsdictionary* alertdict = (nsdictionary*) alert;

ALERTSTR = [alertdict objectforkey:@ "Body"];

}

Application. applicationiconbadgenumber = [[Apsinfo Objectforkey:@ "badge"] IntegerValue];

if ([application applicationstate] = = uiapplicationstateactive && alertstr! = nil)

{

Uialertview* Alertview = [[uialertview alloc] initwithtitle:@ "Pushed222 Message" Message: Alertstr delegate:nil cancelbuttontitle:@ "OK" otherbuttontitles: Nil];

[Alertview show];

}

}

Server code

<?php

Put your device token here (without spaces):

$deviceToken = ' 7d40b88~~~~~80013f376603ff7a0237509336d6616ae04564b3412b86 ';

Put your private key ' s passphrase here:

$passphrase = ' 198~~~~30 ';

Put your alert message here:

$message = ' My first push notification! ' ;

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

$ctx = Stream_context_create ();

Stream_context_set_option ($ctx, ' SSL ', ' Local_cert ', ' Apns-dev.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: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,

' 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;

Else

Echo ' Message successfully delivered ' . Php_eol;

Close the connection to the server

Fclose ($fp);

      reprinted from  http://www.2cto.com/kf/201401/275788.html

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.