Use APNS for message push
Principle
APNS is an abbreviation for Apple push Notification Service (Apple push server) and is Apple's server.
APNs push can be divided into three stages:
First stage: Push Server application Package the message to be sent, the logo of the target iphone, and send it to APNs.
Phase II: APNs in its own list of registered push service iphones, find the iphone with the appropriate logo and send the message to iphone.
The third stage: The iphone sends the message to the appropriate application and follows the settings to eject the push notification.
The detailed process is as follows:
1, the first is the application registration message push service.
2. APNs returns Devicetoken to the application.
3. The application sends Devicetoken to the push server program.
4. The service-side program sends messages to the APNS service.
5. The APNs service sends the message to the iphone app.
Certificate generation
There are many detailed steps on the web for certificate generation, which are no longer explained here.
The resulting certificate contains the following four
1, Pushnotification.certsigningrequest
2. Aps_development.cer (Download the generated certificate that supports the push service.) )
3, Pushnotificationdevprofile.mobileprovision
4, PUSHNOTIFICATION.P12
Directly below the code.
Client
1. Application Registration Message Push service
In APPDELEGATE.M (BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (NSDictionary *) The Launchoptions method joins the registration message notification Push service.
1-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions2 {3 //Determines whether the application starts 4 if triggered by a remote message notification ([launchoptions Objectforkey:uiapplicationlaunchoptionsremotenotificationkey] !=nil) {5 NSLog (@ "Remote message notification triggers application launch"), 6 }7 //Message Push registration 8 [[UIApplication sharedapplication] registerforremotenotificationtypes:uiremotenotificationtypesound| Uiremotenotificationtypealert| UIREMOTENOTIFICATIONTYPEBADGE];9}
2, the method of receiving Devicetoken
Add the following two proxy methods to the APPDELEGATE.M of the project
1-(void) Application: (UIApplication *) application Didregisterforremotenotificationswithdevicetoken: (NSData *) Devicetoken {2 nsstring *token = [NSString stringwithformat:@ "%@", Devicetoken]; 3 //Get terminal equipment identification, After the identity gets sent to the server side, the server-side push message to APNs need to know the identity of the terminal, APNs through the registered terminal identity to find terminal equipment. 4 NSLog (@ "My token is:%@", token); 5} 6-(void) Application: (UIApplication *) application Didfailtoregisterforremotenotificationswitherror: ( Nserror *) Error { 7 nsstring *error_str = [NSString stringWithFormat: @ "%@", error]; 8 NSLog (@ "Failed to get token, error:%@", error_str);
3, receive the message processing method
The message receive processing agent method is added to the project APPDELEGATE.M.
1-(void) Application: (UIApplication *) Application 2 didreceiveremotenotification: (Nsdictionary *) UserInfo3 {4 / /Handle the received message here. 5 NSLog (@ "Receive Remote notification:%@", UserInfo); 6}
At this point, the code on the iOS side has been coded. (^_^)
Server
Server side can be implemented in PHP, Java,. NET and other languages. This article uses the Java language to implement
1. Import Jar Package
After the project is built, Javapns_2.2.jar, Javapns-jdk16-163.jar, Bcprov-jdk16-145.jar are copied into the project Lib directory.
2. Build the. p12 file (. NET or Java, etc.) used by the server side
Execute the following commands under the Mac Terminal:
(1), convert Aps_development.cer to APS_DEVELOPMENT.PEM format
$ OpenSSL x509-in aps_development.cer-inform der-out aps_development.pem-outform PEM
(2), convert the private key in P12 format to PEM
$ OpenSSL pkcs12-nocerts-out push_noenc.pem-in PUSHNOTIFICATION.P12
(3). Create a P12 file
$ OpenSSL pkcs12-export-in aps_development.pem-inkey push_noenc.pem-certfile pushnotification.certsigningrequest- Name "Aps_development"-out aps_development.p12
This way we get a certificate file for use in a background application such as. NET or Java: APS_DEVELOPMENT.P12
3. Write server-side code
1 package com.push.server; 2 Import Java.io.FileInputStream; 3 Import java.io.FileNotFoundException; 4 Import java.io.IOException; 5 Import Java.util.ArrayList; 6 Import java.util.List; 7 Import java.util.Properties; 8 9 Import Javapns.devices.Device; Ten import Javapns.devices.implementations.basic.BasicDevice; Import Javapns.notification.AppleNotificationServerBasicImpl; Import Javapns.notification.PushNotificationManager; Import Javapns.notification.PushNotificationPayload; Import javapns.notification.PushedNotification; public class Sendtoapns {17//Devicetoken obtained from client, in order to test, set a fixed value of the private static final String Device_toke N = "13b11050a3fc064b3692e25c0fbd3b774b39ecb0c55a51ff4fb1373e004577a0"; list<string> Devicetoken = new arraylist<string> (); The public void Send () {24///certificate file (. p12) directory on server side String FilePath = null; String path = This.getclass (). GetClassLoader (). GetResource ("/"). GetPath (); FilePath = Java.net.URLDecoder.decode (Path, "Utf-8"); The catch (Exception e) {e.printstacktrace (); System.out.println ("FilePath = "+ FilePath); Certificatepath String = (FilePath + "CONF/IOS_DEVELOPMENT.P12"); 34//Get password for IOS_DEVELOPMENT.P12 properties prop = new properties (); FileInputStream FIS = null; PNS = new FileInputStream (FilePath + "conf/pushmessage.properties"); 39 40 } catch (FileNotFoundException e) {$//TODO auto-generated catch block e.printstacktr Ace (); Prop.load} (IOException e) {//TODO} (FIS) Auto-generated Catch block E.printstacktrace (); A. * String Certificatepassword = prop.getproperty ("password"); 51 52//build SentMessage in String message= "{' aps ': {' alert ': ' This is a push message '}}"; 54 55//Set-up logo devicetoken.add (device_token); 57//Send Message Sendpush (Devicetoken, Certificatepath, Certificatepassword, message, 4, false); 59} 60 61/************************************************ 62 test with URL gateway.sandbox.push.apple.com/ 2195 63 official release with URL gateway.push.apple.com/2195 Javapns_2.2.jar must be 65 *********************************** //** * @param tokens the unique identity of the iphone device * @param path. P12 Certificate Files * @para M password. The password for the P12 certificate file * @param message content sent by MSG * @param count * @param sendcount true One Send false to a mass of sendpush * * * public void list<string> tokens,string path, string password, string Message,integer Bayi Count,boolean sendcount) {try {$//message:{"APS": {"alert": "A New Message"}} 8 5 Pushnotificationpayload payLoad = Pushnotificationpayload.fromjson (message); //payload.addalert (message); Payload.addbadge (count); Payload.addsound ("Default"); Pushnotificationmanager Pushmanager = new Pushnotificationmanager (); //True official release with URL//False test with URL pushmanager.initializeconnection (new Appleno Tificationserverbasicimpl (path, password, 94, false)); list<pushednotification> notifications = new arraylist<pushednotification> (); 97//Push Mode 98 if (sendcount) {System.out.println ("-------now do a one-push-------"); 10 0 Device device = new Basicdevice (); 101 Device.settoken (Tokens.get (0)); 102 Pushednotification notification = pushmanager.sendnotification (device, PayLoad, 103 104 true); notific ATIONS.ADD (notification); 106 } else {107 System.out.println ("------now mass-------"); 108 list<device> Device = New Arraylist<device> (); 109 for (String token:tokens) {device.add (new Basi CDevice (token)); 111}112 notifications = pushmanager.sendnotifications (payLoad, device); 11 3}114 list<pushednotification> failednotifications = pushednotification.findfailednotif ICATIONS116 117 (notifications); 118 list<pushednotification> successfulnotifications = 119 PushedNot Ification.findsuccessfulnotifications (notifications); 121 int failed = failednotifications.size (); 122 int successful = Successfulnotifications.size () 123 124 if (Successful > 0 && failed = = 0) {//log.debug ("-----All notifications pushed success (" + 126 127 successfulnotifications.size () + "): 128 SYSTEM.OUT.PRINTLN ("-----All notifications pushed success (" + 129-successfulnotifications.size () + "):"); 131 } successful Else if (= = = 0 && failed > 0) {133//log.debug ("-----All n Otifications pushed failed ("+ failednotifications.size () + 134 135"): ") 136 System.out.println ("-----All Notifications pushed failed ("+ 137 138 failednotifications.size () +"): "), 139}, or if (suc Cessful = = 0 && failed = = 0) {141 System.out.println ("No notifications could be sent, probably Bec Ause of a critical 142 143 error ") 144} 145 else {146//log.debug ("------Some not Ifications pushed failed ("+ failednotifications.size147 148 () +"): ") 149//log.debug ("------Others pus Hed success ("+ successfulnotifications.size () + 151"): "System.out.println ("------Some Notifica tions pushed failed ("+ 153 154 Failednotifications.size () + "):") 155 System.out.println ("------Others pushed success (" + succes Sfulnotifications.size () 156 157 + "): 158}159 pushmanager.stopconnection (); 160 161 } catch (Exception e) {162 e.printstacktrace (); 163}164}165}
At this point, the server-side code is finished. (^_^)
Features of APNs push
The following points are summarized from the APNs documentation:
1, provide single send and mass function.
2, when the user's phone is not online (there may be no signal or shutdown), APNs will store and forward, and so on when the user is sent online.
3, if the user is not online for a long time, this message will be ignored.
4, if the user is not on the line, the notification will be merged, will only keep the latest one.
5, payload, is the last generation of the JSON, not more than 256 bytes. If it is exceeded, it is recommended to remove some unnecessary parameters, alert is the hint
The number of words in the message decreases.
6, send a successful no return, only send failed to return.
7, if there is error-response, then the notice after this will need to be re-sent.
8. If something goes wrong, you need to close the current connection and reconnect again. The notification ID returned in Error-response can help us find out which error
, so you can know what needs to be re-sent.
9, do not repeatedly connect, terminate the connection with APNs, otherwise it will be APNs refused to connect.
10. APNs's feedback service will return the devicetoken of those devices that have been uninstalled. For these tokens, you won't have to send them again next time. Can save
Point Resources. Note that the feedback interface reads once, the APNs will empty its list, and the next time it reads, it returns the two reads between the two
A new generation of devicetoken during the period
Message Push APNs