1. iOS client Programming
The push notification technology can run on Mac OS X and iOS systems. This chapter mainly introduces the programming of IOS clients. The push notification programming is relatively simple. The key to programming is to obtain the token, this is returned from apns and then submitted to the content provider. Let's take a look at some preparations before development.
Configure the xcode Project
You need to configure the IOS push application in the xcode project. These configurations are mainly used to set the code signature ID. The configuration profile (provisioning profiles) is the prerequisite for the code signature ID ).
With the configuration profile, you can set the code signature identifier. You need to download the profile to your local computer. You need to select this configuration profile for the code signature identifier. Select tagets → mynotes → code signing identity and select your own code signature ID.
After setting, you can start encoding.
Code Implementation
The Code Implementation of push notifications consists of two steps: the first step is to register and receive notifications, and the second step is to receive registration results. These tasks are implemented in the application delegate object appdelegate.
Let's first look at the registration code
-(BOOL) application: (UIApplication *) application
didFinishLaunchingWithOptions: (NSDictionary *) launchOptions
{
// Register to receive notification types
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge
| UIRemoteNotificationTypeSound
| UIRemoteNotificationTypeAlert)];
// Set icon mark
application.applicationIconBadgeNumber = 1;
return YES;
}
The registration process is relatively long. It returns from Apple through APNS. The callback method code after the registration is completed:
-(void) application: (UIApplication *) application
didRegisterForRemoteNotificationsWithDeviceToken: (NSData *) deviceToken
{
NSLog (@ ”设备 Token:% @”, deviceToken); ①
NSString * tokeStr = [NSString stringWithFormat: @ "% @", deviceToken]; ②
if ([tokeStr length] == 0) {
return;
}
NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString: @ "\ <\>"];
tokeStr = [tokeStr stringByTrimmingCharactersInSet: set]; ③
tokeStr = [tokeStr stringByReplacingOccurrencesOfString: @ "" withString: @ ""]; ④
NSString * strURL = @ ”http://192.168.1.103/push_chat_service.php”; ⑤
NSURL * url = [NSURL URLWithString: strURL];
ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL: url];
[request setPostValue: tokeStr forKey: @ "token"];
[request setPostValue: @ "98Z3R5XU29.com.51work6.PushChat" forKey: @ "appid"];
[request setDelegate: self];
NSLog (@ "Send to server");
[request startAsynchronous]; ⑥
}
-(void) application: (UIApplication *) application
didFailToRegisterForRemoteNotificationsWithError: (NSError *) error
{
NSLog (@ "Failed to get token:% @", error);
}
2. Push server programming
The content provider receives the device token and saves it. When new content needs to be pushed, they will start a service program to push their content device by device. In the specific process of pushing, it is not directly sent by the content provider to the user device, but the service program establishes a trusted connection with the APNS communication, and then pushes the data to the APNS, and then the APNS uses the secure channel to push to the user device.
If we want to write a push service program for a content provider, we need to perform SSL authentication programming and construct an APNS data packet. The data packet is divided into three main parts: Command, deviceToken, and Payload. The payload cannot exceed 256 bytes and is in JSON format, for example:
{"Aps": {
“Alert”: ”You got your emails.”,
"Badge": 9,
"Sound": ”bingbong.aiff”
}
}
As a launching service program, it can be implemented in many computer languages. If it is easy to manage, use PHP, Java, .NET, or even Note.js. This book focuses on PHP and Java to write push service programs.
Use PHP to implement push service
PHP is a very good server-side script. It has not been eaten up by JavaEE and .NET for so many years, which shows that it has something extraordinary. PHP programming is simple. Many people use it intentionally, and implementing the push service in this chapter is also very simple. The following code is the PHP code that implements push:
<? php
$ deviceToken = ’1634899aef6c71ed5c0667d6658677a914c5ec3b545887e8173854970dee24db’;
// Pushing method, including content and sound
$ body = array (“aps” => array (“alert” => ‘Happy New Year. from PHP’, ”badge” => 11, ”sound” => ’default’)); ①
// Create data flow context object
$ ctx = stream_context_create ();
// Set pem format file
$ pem = ”apns-dev.pem”; ②
// Set the local authentication certificate of the data flow context
stream_context_set_option ($ ctx, ”ssl”, ”local_cert”, $ pem); ③
$ pass = "51work6.com";
// Set the password of the data flow context
stream_context_set_option ($ ctx, ’ssl’, ’passphrase’, $ pass); ④
// Product release APNS server, gateway.push.apple.com
// Test the APNS server, gateway.sandbox.push.apple.com
// socket communication
$ fp = stream_socket_client (“ssl: //gateway.sandbox.push.apple.com: 2195 ″, $ err, $ errstr, 60,
STREAM_CLIENT_CONNECT, $ ctx); ⑤
if (! $ fp) {
echo "Connection failed.";
return;
}
print ”Connect OK \ n”;
// Load information, JSON encoding
$ payload = json_encode ($ body); ⑥
// Build the sent binary information
$ msg = chr (0). pack (“n”, 32). pack (“H *”, str_replace (‘’, ”, $ deviceToken))
. ack (“n”, strlen ($ payload)). $ payload; ⑦
echo ”Send message:”. $ payload. ”\ n”;
fwrite ($ fp, $ msg);
fclose ($ fp);
?>
Open a terminal window and execute the following commands:
$ openssl pkcs12 -in certificate. p12 -out apns-dev.pem -nodes
Enter Import Password:
MAC verified OK
After you press Enter, you need to enter the password. This password is the password set when exporting "Certificate.p12".
After the PHP code is written, you can run PHP. There are two ways to run it. One is to put this file in the Apache HTTP server directory, and ensure that Apache is installed and PHP, and then run it with a browser. Enter http in the browser : //localhost/phpPNs/Pusher.php, this URL is a PHP file on my own Apache HTTP server.
Another method is much simpler. We do not need to install the Apache HTTP server, we only need to install the PHP interpreter. We run the following command in the terminal:
$ php -f Pusher.php
Connect OK
Send message: {“aps”: {“alert”: ”\ u65b0 \ u5e74 \ u597d. From PHP”, ”badge”: 11, ”sound”: ”default”}}
In this way, you can push the notification. If everything is pushed successfully, the user's device can receive the notification.
Use Java Push Service
Above we introduced the push service program implemented by PHP. The basic process of writing in other languages is the same. In this section, we introduce the Java push service program. Since the specific process is the same as PHP, here we will no longer write the Java implementation code ourselves, but use the javapns (http://code.google.com/p/javapns/) class library that others have packaged, which encapsulates In view of the details of socket implementation, it becomes easier to develop.
The following code is the Java code that implements the push:
package com._51work6;
import javapns.Push;
import javapns.notification.PushNotificationPayload;
public class Pusher {
public static void main (String [] args) {
try {
PushNotificationPayload payload = new PushNotificationPayload (); ①
payload.addCustomAlertBody ("Happy New Year! from Java"); ②
payload.addBadge (11); ③
payload.addSound ("default"); ④
Push.payload (payload, ”ssl / certificate.p12 ″,” 51work6.com ”, false,
"1634899aef6c71ed5c0667d6658677a914c5ec3b545887e8173854970dee24db"); ⑤
} catch (Exception e) {
e.printStackTrace ();
}
}
}
The above code also depends on the following libraries: bcprov-jdk15-146.jar, JavaPNS_2.2.jar and log4j-1.2.15.jar. Among them, bcprov-jdk15-146.jar and JavaPNS_2.2.jar can be downloaded at http://code.google.com/p/javapns/. Log4j-1.2.15.jar to http://logging.apache.org/log4j/1.2/download.html to download.
We will not introduce the operation of this Java program. It is a Java Application that can be run in a jre environment. We can make it a JavaWeb program so that notifications can be sent in the browser.