APNS for message pushing and apns for message pushing
Push messages using APNS
Principle
APNS is the abbreviation of Apple Push Notification Service (Apple Push server). It is an Apple server.
APNS push can be divided into three phases:
Phase 1: The push server application 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 delivers the sent message to the corresponding application, and the push notification pops up according to the settings.
The detailed process is as follows:
1. First, the application registers the message PUSH Service.
2. APNS returns the deviceToken to the application.
3. The application sends the deviceToken to the push server.
4. The server program sends a message to the APNS service.
5. The APNS Service sends messages to the iPhone application.
Certificate generation
There are many detailed steps for certificate generation on the Internet, which are not described here.
The final certificate consists of 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
The following code is used directly.
Client
1. register the message PUSH Service for the Application
Add the register Message notification PUSH Service in the (BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions method of AppDelegate. m.
1-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions2 {3 // determine whether the application is triggered by a remote Message notification to start 4 if ([launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey]! = Nil) {5 NSLog (@ "remote Message notification triggered application startup"); 6} 7 // message push registration 8 [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge]; 9}
2. Method for receiving deviceToken
Add the following two proxy methods to AppDelegate. m of the project:
1-(void) application :( UIApplication *) application didRegisterForRemoteNotificationsWithDeviceToken :( NSData *) deviceToken {2 NSString * token = [NSString stringWithFormat: @ "% @", deviceToken]; 3 // obtain the identifier of the terminal device. After the identifier is obtained, it must be sent to the server. When the server pushes a message to APNS, it must know the identifier of the terminal, APNS finds the terminal device through the registered terminal ID. 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 ); 9}
3. Message receiving Methods
Add the message receiving and processing proxy method to the project AppDelegate. m.
1-(void) application :( UIApplication *) application 2 didReceiveRemoteNotification :( NSDictionary *) userInfo3 {4 // process received messages here. 5 NSLog (@ "Receive remote notification: % @", userInfo); 6}
Now, the IOS code is complete. (^_^)
Server
The server can be implemented in php, Java,. net, and other languages. This article is implemented in Java
1. Import the jar package
After the project is created, copy the jar packages JavaPNS_2.2.jar, javapns-jdk16-163.jar, and bcprov-jdk16-145.jar to the lib directory of the project.
2. Generate the. p12 file used by the server (. net, Java, and other background files)
Run the following command on 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
In this way, we get the certificate file aps_development.p12 used in background applications such as. net or java.
3. Write server 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; 10 import javapns. devices. implementations. basic. basicDevice; 11 import javapns. notification. applenotifserverserverbasicimpl; 12 import javapns. notification. pushNotificationManager; 13 import javapns. notification. pushNotificationPayload; 14 import javapns. notification. pushedNotification; 15 16 public class SendToAPNS {17 // The deviceToken obtained from the client. For test, set a fixed value of 18 private static final String DEVICE_TOKEN = 19 20 "token "; 21 List <String> deviceToken = new ArrayList <String> (); 22 23 public void send () {24 // Certificate file (. p12) in the server directory 25 String filePath = null; 26 try {27 String path = this. getClass (). getClassLoader (). getResource ("/"). getPath (); 28 filePath = java.net. URLDecoder. decode (path, "UTF-8"); 29} catch (Exception e) {30 e. printStackTrace (); 31} 32 System. out. println ("filePath =" + filePath); 33 String certificatePath = (filePath + "conf/ios_development.p12"); 34 // obtain the ios_development.p12 password 35 Properties prop = new Properties (); 36 FileInputStream FCM = null; 37 try {38 Fi = new FileInputStream (filePath + "conf/pushmessage. properties "); 39 40} catch (FileNotFoundException e) {41 // TODO Auto-generated catch block 42 e. printStackTrace (); 43} 44 try {45 prop. load (FCM); 46} catch (IOException e) {47 // TODO Auto-generated catch block 48 e. printStackTrace (); 49} 50 String certificatePassword = prop. getProperty ("password"); 51 52 // construct the sent message 53 String message = "{'aps ': {'alert ': 'This is a push message'} "; 54 55 // do not identify 56 deviceToken. add (DEVICE_TOKEN); 57 // send message 58 sendpush (deviceToken, certificatePath, certificatePassword, message, 4, false ); 59} 60 61 /*********************************** * ************ 62 URL gateway.sandbox.push.apple.com/2195 63 official release of URL gateway.push.apple.com/2195 64 javaPNS_2.2.jar must be 65 ******** **************************************** * **/66/** 67 * @ param tokens unique identifier of the iphone device 68 69 * @ param path. p12 Certificate file path 70 71 * @ param password. p12 Certificate file Password 72 73 * @ param message content 74 75 * @ param count 76 77 * @ param sendCount true one-to-one sending false Mass Sending 78 79 */80 public void sendpush (List <String> tokens, string path, String password, String message, Integer 81 82 count, boolean sendCount) {83 try {84 // message: {"aps": {"alert ": "A new message"} 85 PushNotificationPayload payLoad = PushNotificationPayload. fromJSON (message); 86 // payLoad. addAlert (message); 87 payLoad. addBadge (count); 88 payLoad. addSound ("default"); 89 90 PushNotificationManager pushManager = new PushNotificationManager (); 91 // true official release URL 92 // false test URL 93 pushManager. initializeConnection (new AppleNotificationServerBasicImpl (path, password, 94 95 false); 96 List <PushedNotification> notifications = new ArrayList <PushedNotification> (); 97 // push method 98 if (sendCount) {99 System. out. println ("------- now one-to-one push -------"); 100 Device device = new BasicDevice (); 101 device. setToken (tokens. get (0); 102 PushedNotification notification = pushManager. sendNotification (device, payLoad, 103 104 true); 105 notifications. add (notification); 106} else {107 System. out. println ("------ send group now -------"); 108 List <Device> device = new ArrayList <Device> (); 109 for (String token: tokens) {110 device. add (new BasicDevice (token); 111} 112 notifications = pushManager. sendNotifications (payLoad, device); 113} 114 115 List <PushedNotification> failedNotifications = PushedNotification. findfailednotifs1s116 117 (notifications); 118 List <PushedNotification> successfulNotifications = 119 120 PushedNotification. findSuccessfulNotifications (notifications); 121 int failed = failedNotifications. size (); 122 int successful = successfulications ications. size (); 123 124 if (successful> 0 & failed = 0) {125 // log. debug ("----- All registrications pushed success (" + 126 127 successfulNotifications. size () + "):"); 128 System. out. println ("----- All communications pushed success (" + 129 130 successfulNotifications. size () + "):"); 131} 132 else if (successful = 0 & failed> 0) {133 // log. debug ("----- All notifications pushed failed (" + failedNotifications. size () + 134 135 "):"); 136 System. out. println ("----- All communications pushed failed (" + 137 138 failedications. size () + "):"); 139} 140 else if (successful = 0 & failed = 0) {141 System. out. println ("No such notifications cocould be sent, probably because of a critical 142 143 error"); 144} 145 else {146 // log. debug ("------ Some notifications pushed failed (" + failedNotifications. size147 148 () + "):"); 149 // log. debug ("------ Others pushed success (" + successfulNotifications. size () + 150 151 "):"); 152 System. out. println ("------ Some notifications pushed failed (" + 153 154 failedications. size () + "):"); 155 System. out. println ("------ Others pushed success (" + successfulNotifications. size () 156 157 + "):"); 158} 159 pushManager. stopConnection (); 160 161} catch (Exception e) {162 e. printStackTrace (); 163} 164} 165}
So far, the server code is complete. (^_^)
Features of APNS push
This document summarizes the following points:
1. Provides Single sending and Group Sending functions.
2. When a user's mobile phone is offline (there may be no signal or shutdown), APNs will store and forward the phone and send it again when the user is online.
3. If the user is offline for a long time, this information will be ignored.
4. If the user is not online, the notification will be merged and only the latest one will be retained.
5. payload is the last Json file generated, which must not exceed 256 bytes. If this parameter is exceeded, we recommend that you remove unnecessary parameters.
The number of words in the information is reduced.
6. If the message is sent successfully, no response is returned.
7. If error-response exists, the subsequent notifications must be resent.
8. If an error occurs, close the current connection and re-connect the connection. The notification ID returned in error-response helps us identify the error.
So that you can know what needs to be resold.
9. Do not connect to APNS multiple times or terminate the connection. Otherwise, the connection will be rejected by APNS.
10. The feedback service of APNS returns the deviceToken of the unmounted devices. For these tokens, you do not need to send them again next time. Save
Point Resource. Note that when the feedback interface reads data once, APNS clears its list. The returned value is
The newly generated deviceToken