IOS APNs push front-end and back-end (Java) code

Source: Internet
Author: User
Tags ssl certificate

The principle of push:

The working mechanism of push can be simply summed up as: provider refers to the push server for an iphone software, which I will use. NET as a provider. APNS is an abbreviation for Apple push Notification Service (Apple push server) and is Apple's server. Can be divided into three stages. First stage: The Push server application packages the message to be sent, the identity of the iphone, and sends it to APNS. Phase II: APNs in its own list of iphone's registered push services, look for an iphone with a corresponding logo and send the message to the iphone. The third stage: The iphone sends the message to the appropriate application and follows the settings to eject the push notification. iOS front-end push message steps:1. Application Registration message notification, the code is as follows: [Note: iOS7 and iOS8 registration notice is not the same Oh!!! ]
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions{// Message push [self msgpush];} /** message push **/-(void) msgpush{//push in the form of: tag, sound, prompt if (is_ios8) {//1. Create a message above the action to be added (displayed as a button) uimutable        Usernotificationaction *action = [[Uimutableusernotificationaction alloc] init]; Action.identifier = @ "action";//button [email protected] "Accept";//button Title Action.activationmode = Uiusern        otificationactivationmodeforeground;//start the program when clicked//action.authenticationrequired = YES;                Action.destructive = YES;        Uimutableusernotificationaction *action2 = [[Uimutableusernotificationaction alloc] init];        Action2.identifier = @ "Action2";        [email protected] "Reject";        Action2.activationmode = uiusernotificationactivationmodebackground;//When clicked does not start the program, in the background processing action.authenticationrequired = yes;//needs to be unlocked for processing if Action.activationmode = UiusernotificationactivationmOdeforeground; the attribute is ignored; action.destructive = YES;        2. Create a Category collection of actions (buttons) uimutableusernotificationcategory *categorys = [[Uimutableusernotificationcategory alloc] init]; Categorys.identifier = @ "alert";//the only indication of this set of actions, when the push notification is also based on this to differentiate [Categorys Setactions:@[action,action2] Forcont                Ext: (uiusernotificationactioncontextminimal)]; 3. Create the uiusernotificationsettings and set the display class type of the message uiusernotificationsettings *notisettings = [uiusernotificationsetting S settingsfortypes: (Uiusernotificationtypebadge | Uiusernotificationtypealert |        Uiremotenotificationtypesound) Categories:[nsset Setwithobjects:categorys, Nil]];    [[UIApplication sharedapplication] registerusernotificationsettings:notisettings];  }else{[[UIApplication sharedapplication] Registerforremotenotificationtypes:uiremotenotificationtypebadge | Uiremotenotificationtypesound |    Uiremotenotificationtypealert]; }    }

-(void) Application: (UIApplication *) application didregisterusernotificationsettings: (Uiusernotificationsettings * ) notificationsettings

{

Registering Remote Notifications

[Application registerforremotenotifications];

}

2, iOS and APNs server to Devicetoken. The application accepts Devicetoken. "The code is as follows:"

3. The application sends Devicetoken to the push server end program

-(void) Application: (UIApplication *) application Didregisterforremotenotificationswithdevicetoken: (NSData *) devicetoken{    MyLog (@ "MyToken =%@", devicetoken);    Save Tokens    [Config savetoken:[nsstring stringwithformat:@ "%@", Devicetoken]];

Send Devicetoken to Server

[Self initnetworkstate:[nsstring stringwithformat:@ "%@", Devicetoken]];

}

-(void) Initnetworkstate: (NSString *) PToken

{

Nsdictionary *dicjson = [Packjsonformine Packtokenjson:ptoken];

Nserror *error;

NSData *jsondata = [nsjsonserialization datawithjsonobject:dicjson options:nsjsonwritingprettyprinted Error: & ERROR];

Nsmutabledata *tempjsondata = [Nsmutabledata datawithdata:jsondata];

request = [ASIHTTPRequest requestwithurl:[nsurl Urlwithstring:ids_url_token]];

[Request setrequestmethod:@ "POST"];

[Request Setpostbody:tempjsondata];

[Request Setdelegate:self];

[Request Setdidfailselector: @selector (requestlogfailed:)];

[Request Setdidfinishselector: @selector (requestlogfinish:)];

[Request startasynchronous];

}

/**

Failed to send token

**/

-(void) requestlogfailed: (ASIHTTPRequest *) Requests

{

MyLog (@ "Send token to server failed%@", [Requests responsestring]);

}

/**

Send token successfully

**/

-(void) Requestlogfinish: (ASIHTTPRequest *) Requests

{

[Config Savetokenflag];

}

4. The service-side program sends messages to the APNS service. 5. The APNs service sends the message to the iphone app. "Note: There are two kinds of processing pushes: The running program receives the push message, Alerat the popup, and the notification bar displays when the lock screen"
#pragma mark-processing the message content of the push-(void) Application: (UIApplication *) application didreceiveremotenotification: (Nsdictionary *    ) userinfo{self.urlstr = [userInfo valueforkey:@ "link"];        Self.message = [[UserInfo objectforkey:@ "APS"] objectforkey:@ "alert"]; [UIApplication sharedapplication].applicationiconbadgenumber = [UIApplication sharedapplication].        Applicationiconbadgenumber = [[[UserInfo objectforkey:@ "APS"] objectforkey:@ "badge"] intvalue]; Note: When opening an app, a box alert is required, otherwise the user cannot see the push message if (application.applicationstate = = uiapplicationstateactive) {if (Self.urlStr.length > 0)            {Customios7alertview *alertview = [[Customios7alertview alloc] init];            Custom Alertview [Alertview setcontainerview:[self CreateView];            [Alertview setbuttontitles:[nsmutablearray arraywithobjects:@ "Off", @ "View", Nil]];            [Alertview Setbackgroundcolor:[uicolor Clearcolor];            [Alertview setdelegate:self]; [AlertView Setusemotioneffects:true];        [Alertview show];            }else{Customios7alertview *alertview = [[Customios7alertview alloc] init];            Custom Alertview [Alertview setcontainerview:[self CreateView];            [Alertview setbuttontitles:[nsmutablearray arraywithobjects:@ "Off", Nil]];            [Alertview Setbackgroundcolor:[uicolor Clearcolor];            [Alertview setdelegate:self];            [Alertview Setusemotioneffects:true];        [Alertview show]; }}else{if (Self.urlStr.length > 0) {webviewcontroller *WEBVIEWC = [[Webviewcontroller alloc] In            It];            Webviewc.link = Self.urlstr;            [Tool Showhidetoolbar:hide];        [Navintergralcontroller PUSHVIEWCONTROLLER:WEBVIEWC Animated:yes]; }    }    }

Both the iphone client and APNs, provider and APNs need to be connected through a certificate. The following describes the production of the certificate used.

I. CSR documents

1. Generate Certificate Signing Request (CSR) 2. Fill in your email and common name and save to hard drive Click Continue: This generates a pushtest.certsigningrequest file locally. Second, the SSL certificate file and related certificate production process details, please see the following blog content:http://www.cnblogs.com/imlucky/p/3419581.htmlTests are required when testing in push. P12 files and published. P12 File Background code: VI. Java Background code: public static void Main (string[] args) throws Exception
{
Try
{
The Devicetoken obtained from the client, in order to test the simple, write a fixed test device identity.
String Devicetoken = "Df779eda 73258894 5882ec78 3ac7b254 6ebc66fe fa295924 440d34ad 6505f8c4" System.out.print ln ("Push Start devicetoken:" + Devicetoken);
Defining Message Patterns
PayLoad PayLoad = new PayLoad ();
Payload.addalert ("This is test!");
Payload.addbadge (1);//The number of message push marks, the number shown in the small red circle.
Payload.addsound ("Default");
Register Devicetoken
Pushnotificationmanager Pushmanager = Pushnotificationmanager.getinstance ();
Pushmanager.adddevice ("IPhone", Devicetoken);
Connection APNs
String host = "gateway.sandbox.push.apple.com";
String host = "gateway.push.apple.com";
int port = 2195; String Certificatepath = "C:/PUSHTEST.P12";//*.P12 file location generated earlier for the Java Background Connection APNs service
String Certificatepassword = "123456";//p12 file password.
Pushmanager.initializeconnection (host, Port, Certificatepath, Certificatepassword, sslconnectionhelper.keystore_ TYPE_PKCS12);
Send push
Device client = Pushmanager.getdevice ("IPhone");
SYSTEM.OUT.PRINTLN ("Push message:" + client.gettoken () + "\ n" +payload.tostring () + "");
Pushmanager.sendnotification (client, payLoad);
Stop Connection APNs
Pushmanager.stopconnection ();
Delete Devicetoken
Pushmanager.removedevice ("IPhone");
System.out.println ("Push End");
}
catch (Exception ex)
{
Ex.printstacktrace ();
}
}
} so you are!!!!!!!

IOS APNs push front-end and back-end (Java) code

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.