Implementation of IOS push function (javapns)

Source: Internet
Author: User
Document directory
  • (3) hybrid mode
IOS push is implemented in the following steps:
  1. Create push SSL Certification
  2. Register the push function on the IOS client and obtain the devicetoken
  3. Use provider to send push messages to apns
  4. The IOS client receives and processes messages sent from apns.
Create push SSL Certification

Log on to pai.apple.com and create a new app ID. The bundle identifier of this ID must not contain wildcards. Otherwise, the push and IAP functions cannot be enabled. For example, Com. Soso. sosoimage.

On the app IDs list page, click the configure link on the right of the created app ID To Go To The Configure app ID page, and select "enable for app push notification service ". Click the Configure button of the SSL Certificate row in development push. The "Apple push notification service SSL Certificate assistant" dialog box is displayed, which is similar to creating a certificate for development or release.

The developer finally downloads the SSL Certificate push and installs it on the local keychain access. Export to p12 file. You must set a password for export.

In pai.apple.com, create a new provisioning profile and use the ID of the app that we just created that supports the push function. Download and install it locally.

 

Register the push function on the IOS client and obtain the devicetoken

Create a local project. In info. plist, set bundle identifier to the ID of the newly created bundle. Com. Soso. sosoimage. Set code signing identity to the created provisioning profile.

When the program is executed for the first time, the following code is called.

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];

The three parameters represent messages (banners or reminders, determined by the user's setting, and the program cannot be changed), numbers, and sounds.

Add two methods in appdelegate. M.

// Call back this method after the iPhone obtains the devicetoken from the apns server-(void) Application :( uiapplication *) app token :( nsdata *) devicetoken {nsstring * dt = [[devicetoken description] stringbytrimmingcharactersinset: [nscharacterset charactersetwithcharactersinstring: @ "<>"]; nslog (@ "devicetoken: % @", DT);} // an error message is returned after the push function fails to be registered, execute the corresponding processing-(void) Application :( uiapplication *) app didfailtoregisterforremotenotificationswitherror :( nserror *) Err {nslog (@ "Push register error: % @", err. description );}

After obtaining the devicetoken, send it to the provider.

Use provider to send push messages to apns

Provider to send the push information to the apns (Apple push server) program. There are a lot of open source implementations that we use javapns (http://code.google.com/p/javapns ).
First, the provider must have the target devicetoken, which is the Sending target, which exists somewhere after the client sends the devicetoken to the provider.
To install javapns, the jar to be imported is bcprov-jdk15-146.jar, log4j-1.2.15.jar, javapns_2.3_alpha_5.jar.
Put the exported p12 file in the project directory of the provider.
For details about how providers send messages to apns, see notificationtest. Java in javapns. You can also refer to the following example.

(1) display the client icon with a numerical mark
Push.badge(2, keystore, password, false, "7bb8d508e32df651c6c239439737dbd40a88d2461ad2ac1e5dbe49ecea5ccc67");

2 indicates the number to be displayed;

String keystore = "pushcertificates. p12"; // path of the p12 file; string Password = "sosoimage"; // password of the p12 file;

False indicates that the test environment is used, and true should be input when the formal product environment is used.
"Token" is the devicetoken that the client obtains and sends to the provider. This parameter can also be used to input a string [] object to push messages to multiple clients at the same time.

(2) display banners or reminders on the client

The provider can push a message to the client, but the client has the permission to determine the display mode of the message (none, banners, reminders ).

Push.alert("A Message", keystore, password, )false, "7bb8d508e32df651c6c239439737dbd40a88d2461ad2ac1e5dbe49ecea5ccc67");
(3) hybrid mode

Multiple messages, messages, tags, and sounds can be attached to a push message. The following code can be used.

PushNotificationPayload payload = PushNotificationPayload.complex();payload.addAlert("A Message");payload.addBadge(2);payload.addSound("test.aiff");Push.payload(payload, , keystore, password, false, "7bb8d508e32df651c6c239439737dbd40a88d2461ad2ac1e5dbe49ecea5ccc67");

All the above Code may have corresponding exceptions to be thrown and need to be processed. For more usage, refer to http://code.google.com/p/javapns/

The IOS client receives and processes messages sent from apns.

(1) When the program is not started, the user receives the message. You must obtain the message content in didfinishlaunchingwitexceptions of appdelegate. The Code is as follows,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    ...        NSDictionary* payload = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];    if (payload)     {    ...    }    ...}

(2) When the program runs on the front-end, no message prompts (prompt box or banners) are received ). When the program runs in the background and receives a message, a message prompt is displayed. After you click the message to enter the program, the appdelegate didreceiveremotenotification function is called (you need to rewrite it yourself). The message is passed in as a parameter of this function, the Code is as follows:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)payload{     ...}

(3) No matter which function is passed in, the message is always an nsdictionary object. For the processing method, refer to the following code:

- (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 cancelButtonTitle:@"OK" otherButtonTitles:nil];        [alertView show];        }}

 

From: http://blog.csdn.net/worldmatrix/article/details/7634596

 

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.