The things that IOS pushed _ios

Source: Internet
Author: User
Tags openssl openssl x509 strlen

Go straight to the topic and talk about how to simulate push and handle push messages. Before going into the topic, let me say a few key processes:
1, Build push SSL Certification (push certificate)
2. OS Client register push function and get Devicetoken
3. Send push message to APNs with provider
4, the OS client receives processing by the APNS sends the message
Push Flowchart:

Provider: is the server that provides push for the specified iOS device application. If the iOS device application is a client, then provider can be understood as the server (the initiator of the push message)
APNs: Apple push Notification Service (Apples message Push server)
Devices:iOS device, used to receive messages from APNs
Client App:an application on an iOS device used to receive APNS messages to a specified client app (the final responder to the message)
1, take device token
App must register to APNs request to implement push function, after the request succeeds, APNs will return a device's identifier namely Devicetoken to the app, the server needs to specify the push notification target device's Devicetoken when the push notification is sent. After IOS 8 and after, the enrollment push service is divided into four main steps:

    • Using registerusernotificationsettings: Registering the type of push that the application wants to support
    • Registering push features to APNs by calling the Registerforremotenotifications method
    • When the request succeeds, the system returns Devicetoken in the application delegate method, and the reason for the request failure is given in the corresponding delegate method when the request fails.
    • Uploads the Devicetoken to the server, which is used when the server is pushed.

The first of these steps is a new API for iOS 8, so in iOS 7, the first two steps need to be changed to the APIs in iOS 7.
Devicetoken is likely to change, so it needs to be registered and uploaded to your server each time the program starts.

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {if ([ Application Respondstoselector: @selector (registerusernotificationsettings:)]) {NSLog (@ requesting permission for Push notifications ... "); IOS 8 Uiusernotificationsettings *settings = [Uiusernotificationsettings Settingsfortypes:uiusernotificationtypea Lert |
   Uiusernotificationtypebadge |
  Uiusernotificationtypesound Categories:nil];
 [Uiapplication.sharedapplication registerusernotificationsettings:settings];  else {NSLog (@ "Registering device for push notifications ...");//IOS 7 and earlier [uiapplication.sharedapplication Registerforremotenotificationtypes:uiremotenotificationtypealert |
   Uiremotenotificationtypebadge |
 Uiremotenotificationtypesound];
return YES; }-(void) Application: (UIApplication *) application didregisterusernotificationsettings: (uiusernotificationsettings *) Settings {NSLog (@ "Registering device for push NotificatIons ... ");
IOS 8 [Application registerforremotenotifications];
}-(void) Application: (UIApplication *) application Didregisterforremotenotificationswithdevicetoken: (NSData *) token {NSLog (@ "Registration successful, bundle identifier:%@, mode:%@, device token:%@", [Nsbundle.mainbundle bundleident
Ifier], [self modestring], token); }-(void) Application: (UIApplication *) application Didfailtoregisterforremotenotificationswitherror: (NSError *)

Error {NSLog (@ "Failed to register:%@", error);}
 -(void) Application: (UIApplication *) application Handleactionwithidentifier: (NSString *) identifier Forremotenotification: (nsdictionary *) notification Completionhandler: (void (^) ()) Completionhandler {NSLog (@) Received Push notification:%@, identifier:%@ ", notification, identifier);
IOS 8 Completionhandler (); }-(void) Application: (UIApplication *) application didreceiveremotenotification: (nsdictionary *) notification {NSLog ( @ "Received Push notification:%@", notification); Ios 7 and earlier}-(NSString *) modestring {#if DEBUG return @ "Development (sandbox)", #else return @ "Production"; #end

 if}

2, processing push message
1), the program did not start, the user received the message. Need to get message content from Didfinishlaunchingwithoptions in Appdelegate

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {
 //...
 Nsdictionary *payload = [Launchoptions Objectforkey:uiapplicationlaunchoptionsremotenotificationkey];
 if (payload) {
  //...
 }
 //...
}

2, the program is running in the foreground, receive the message will not have a message prompt (hint box or banner). When the program is running in the background, the message will receive a message prompts, click on the message to enter the program, Appdelegate didreceiveremotenotification function will be called, the message to do this function parameters passed in

-(void) Application: (UIApplication *) application didreceiveremotenotification: (
 Nsdictionary *) Payload {NSLOG (@ "Remote notification:%@", [payload description]);  
 nsstring* alertstr = nil; 
 Nsdictionary *apsinfo = [Payload 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:@ "pushed message" message:alertstr Delegate:nil "OK"
  Otherbuttontitles:nil]; 
 [Alertview show]; }
}

3, the semantic notification prompt tone
You can add a custom beep file to the APP's Bundle. You can then specify that the file be played when the notification arrives. You must have the following data formats:

    • Linear PCM
    • MA4 (IMA/ADPCM)
    • Μlaw
    • Alaw

You can package them as AIFF, WAV, or CAF files. The custom sound file time must be less than 30 seconds, and if this time is exceeded, it will be replaced by the system sound.
4, Payload
Payload is part of the notification, and each push notification contains a Payload. It contains the way the system alerts users to the arrival of notifications, and can add custom data. That is, the main data passed by the notification is Payload.
Payload itself is a JSON-formatted string that must contain a dictionary with the APS key. APS can contain one or more of the following fields:
Alert: its contents can be either a string or a dictionary, and if it is a string, it will be displayed in the notification
Badge: The value is a number that indicates how much of the applied corner mark changes when the notification arrives at the device. If you do not use this field, the applied corner will not change. When set to 0 o'clock, the applied corner is cleared.
Sound: Specifies the alert sound file name accompanying the notification presentation. If the specified file is not found or has a default value, the system tone will be used. If it is empty, then there will be no sound.
content-available: This field is used by IOS 7 silent remote notification. You do not need to include this field when you do not use this feature.
If you need to add a custom field, let the server's small partners add an array to the same level as the APS (for example, in JSON):

{"
APs": {"alert": "This is the alert text", "badge": 1, "sound": "Default"},

"server": {"ServerID": 1 , ' name ': ' Server name '}


The Payload that is received in this way will have one more server field.
5, Analog push
is now commonly used in the background server, generally will push the certificate and the private key of the push certificate export P12 to the background staff.
Generate PHP required PEM certificate
6, PHP is a bit naughty, also need to convert to PEM
Prepare:
1), Apple server certificate side set correctly! Pack the certificate, the description file is correct!!
2), download push certificate (CER format), import keychain, ensure private key exists, do not exist to find a computer to create this certificate to come over.
3), exported from the key library ~ ~ Root Certificate ~ ~ (push certificate) private key (P12 format)
Third step the private key of the root certificate here is a pit! Because the creation of an app push certificate can be different from the computer created by the root certificate, that is, the certsigningrequest generated by keychain is not the same, so the private key is not the same, when the PEM is generated, notice to use the private key of the push certificate!
Procedure:
A. Converts a push certificate (. cer) to a. Pem file, executing a command:
OpenSSL x509-in push certificate. Cer-inform der-out push certificate. PEM
B. The private key exported by the push certificate (. P12 File into. pem files:
OpenSSL pkcs12-nocerts-out push certificate private key. pem-in Push Certificate private key .p12 
C. Regenerate the generated two PEM files into a PEM file to consolidate the certificate and private key into a single file:
Cat push certificate. PEM push Certificate private key. PEM >phppush.pem
Then give this phppush.pem to backstage base friends, you can work.
Of course the test push is also more troublesome, need to simulate the real push environment, generally need to help backstage, but encountered some backstage colleagues, they have a strong belief in the chain of contempt, very despise iOS, the heart has long called you "dead before" years, and so many ...
So about debugging push, here are two ways to implement self-push! Don't bother others.
simulate push: push through terminal

<?php//Devicetoken $deviceToken = ' Your Devicetoken ';
The private key password, the input $passphrase = ' 123456 ' when generating the PEM;
Custom push content, with a bit of formatting requirements, details Apple docs $message = array (' body ' => ' you receive a New Order ');
$body [' aps '] = Array (' Alert ' => $message, ' sound ' => ' default ', ' badge ' => 100,);
$body [' type ']=3;
$body [' Msg_type ']=4;
$body [' title ']= ' New Order reminder ';

$body [' msg ']= ' You receive a new message ';
$ctx = Stream_context_create (); Stream_context_set_option ($ctx, ' SSL ', ' Local_cert ', ' Push.pem ');/Remember to put the generated PUSH.PEM in the same directory as this PHP file Stream_context_
Set_option ($ctx, ' SSL ', ' passphrase ', $passphrase); $fp = stream_socket_client (///Here needs special attention, one is to develop the push sandbox environment, one is to release the formal environment of push, Devicetoken is not generic ' ssl:// gateway.sandbox.push.apple.com:2195 ', $err,//' ssl://gateway.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;
$payload = Json_encode ($body); $msg = Chr (0). Pack (' n ', 32). Pack (' h* ', $deviceToken). Pack ('N ', strlen ($payload)).
$payload;
$result = fwrite ($fp, $msg, strlen ($msg)); if (! $result) echo ' message is not delivered '.
Php_eol; else ECHO ' message successfully delivered '.
Php_eol;

 Fclose ($FP);?>

Copy the above code and save it as a push.php
Then generate PUSH.PEM based on the steps above to generate the required PEM certificate for PHP
Two files in the same directory
Execute the following command

superdanny@superdannydemacbook-pro$ PHP push.php 

Result is

Connected to APNs message
successfully delivered

This article has been organized into the "iOS push Tutorial", welcome to learn to read.

The above is about the iOS push of those things, I hope to help you learn.

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.