Programming of Apple push notification service (apns)

Source: Internet
Author: User
Tags key string ssl certificate

-Translated from weimenglee's programming appush ush Notification Services

The iPhone has many restrictions on application running in the background (unless you jailbreak ). Therefore, when you switch to another program, the original program cannot be running. Applications that require continuous connection (such as community network applications) cannot receive real-time information.

To address this restriction, Apple launched the apns (Apple push notification service ). Apns allows devices to be normally connected to Apple's push notification server. When you want to send a push notification to an iPhone application of a user, you can use apns to send a push message to an installed application on the target device.

In this article, you will learn how to create an iOS app using apns.

Create certificate request

The first step to use apns is to generate a certificate request, which is used to apply for an SSL Certificate for development.

1.Open the key string access application.

2.Select "keychainaccess-> certificate assistant-> request a certificate from certificateauthority" (1 ):

3.Enter the required information, select the "saved to disk" option, and click "continue (2 ):

4.Save the certificate request with the default file name (Figure 3): In the pop-up window, click done.

Create app ID

Each iOS app that uses apns must have a unique app ID. In this step, you will learn how to create the app ID used in the push notification.

1.Log on to the iPhone developer program:Http://developer.apple.com/iphone/. Click "iPhone developer program Portal" on the right of the page (figure 4 ):

2.First, we can see the welcome page (figure 5 ):

3.Click "app ID" on the left, and then click "new app ID" on the right (figure 6 ):

4.Enter "pushappid" in the description column and select "generate new" in the "bundle seed ID" column ". In the bundle identifier column, enter "net. learn2develop. mypushapp" and click "Submit" (Figure 7 ):

5.Now you can see the created app ID (figure 8 ):

Configure app

Once an app ID is created, you must configure the app ID for the push notification.

1.Click the configure link on the right of the app ID. The following options are displayed (figure 9 ):

Select enable for Apple push icationicationservice and click "Configure" on the right of "Development push SSL certificate.

2.Next, you will see the "Apple push notification service SSL Certificate assistant" page. Click "continue" (figure 10 ):

3.Click the choose file button and select the address of the previously saved certificate request file. Click Generate (figure 11 ):

4.Your SSL Certificate will be generated. Click "continue" (Figure 12 ):

5.Click Download Now to download the SSL certificate. Click Done (Figure 13 ):

6.The downloaded SSL certificate is named APs. developer. Identity. Cer. Double-click to install the certificate in the key string (figure 14 ). This certificate is used in your program. It allows the program to receive push notifications sent by apns.

Create provisioning Profile

Next, you need to create a provisioning profile to allow the application to be installed on a real device.

1.Return to the iPhone Development Program portal, click the provisioning bar, and click the New Profile button (figure 15 ):

2.Enter mydevicesprofile in the profile name column, and select pushappid in the app ID column. In the devices column, select all devices you want to activate (all devices registered on the devices page of the iPhone developer program portal ). Click Submit (figure 16 ).

3.Provisioning profile will wait for review. After a few seconds, it will be displayed on the page. Click Download to download the provisioning profile (figure 17 ):

4.The downloaded provisioning profile is named mydevicesprofile. mobileprovision.

Activate a device

After creating a provision profile, you can install it on a real device.

1.Connect your iPhone or iPod to your Mac.

2.Drag the downloaded mydevicesprofile. mobileprovision file to the xcode icon on the dock bar.

 

3.Xcode's organizer program starts and selects the device that is currently connected to the machine. You can see that mydevicesprofile has been automatically installed on the device (Figure 18 ).

Create an iPhone application

1.Open xcode and create a view-based application project named applepushnotification.

2.Drag a WAV file (beep.wav in this example) to the xcode resouces folder (figure 19 ).

3.Expand the targets project in xcode, select applepushnotification, press products + I, exit info, and click the Properties tab bar (Figure 20 ):

In the identifier text box, enter net. learn2develop. mypushapp.

 

4.Click the build tab and type code signing in the search input box. On the any iPhone OS device option, select the correct profile (Figure 21 ):

5.In the applepushnotificationappdelegate. M file, enter the following code (bold part ):

# Import "applepushnotificationappdelegate. H"

# Import "applepushnotificationviewcontroller. H"

 

@ Implementation applepushnotificationappdelegate

 

@ Synthesize window;

@ Synthesize viewcontroller;

 

-(Void) applicationdidfinishlaunching :( uiapplication *) Application {

[Window addsubview: viewcontroller. View];

[Window makekeyandvisible];

 

Nslog (@ "registeringfor push notifications ...");

[[Uiapplication sharedapplication]

Registerforremotenotificationtypes:

(Uiremotenotificationtypealert |

Uiremotenotificationtypebadge |

Uiremotenotificationtypesound)];

}

 

-(Void) Application :( uiapplication *) appdidregisterforremotenotifswswithdevicetoken :( nsdata *) devicetoken {

Nsstring * STR = [nsstring

Stringwithformat: @ "device token = % @", devicetoken];

Nslog (STR );

}

 

-(Void) Application :( uiapplication *) appdidfailtoregisterforremotenotificationswitherror :( nserror *) Err {

Nsstring * STR = [nsstringstringwithformat: @ "error: % @", err];

Nslog (STR );

 

}

 

-(Void) Application :( uiapplication *) Application didreceiveremotenotification :( nsdictionary *) userinfo {

For (ID key in userinfo ){

Nslog (@ "key: % @, value: % @", key, [userinfo objectforkey: Key]);

}

}

-(Void) dealloc {

[Viewcontroller release];

[Window release];

[Super dealloc];

}

@ End

6. Press terminal + R to run the program (on the real device ). Press SHIFT + progress + R to display the debugger Console window. View the device token output from the device to the console (Figure 22 ). In, the device token is 38c866dd bb323b39 ffa73487 5e157ee5 a85e0b7c e90d56e9fe145bcc 6c2c594b. Write down device tokens (copy and paste them into a text file)

7. If you check the "Settings" program on the iPhone/iPod, you will find a variety of items (figure 23 ):

Create push notification provider

Push notification provider is an application that sends push notifications to iPhone applications through apns.

There are several steps to send a push notification through apns:
1.Use the SSL Certificate created earlier to communicate with apns;

2.Construct the message carrier to be sent;

3.Send the carrier to apns;

Apns is a stream-based TCP socket. Your provider communicates with it over SSL. Push notifications (including carriers) are sent in binary streams. After establishing a connection with apns, you can maintain the connection and send multiple notifications before the connection is interrupted.

Tip: do not set up or close a connection every time a push notification is sent. Frequent connection establishment or disconnection may be considered as DoS attacks by apns, thus rejecting the request for sending push notifications from providers.

The format of a push notification message is 24:

For more details, seeApple push notification service programming guide.

Payload is a JSON string (up to 256 bytes) that encapsulates the information you send to the iOS app. This is an example of payload:

{

"APs ":{

"Alert": "yougot a new message! ",

"Badge": 5,

"Sound": "beep.wav "},

"Acme1": "bar ",

"Acme2": 42

}

To save the trouble of writing a push notification provider, you can use a Mac OS X application: pushmebaby written by Stefan hafeneger,

1.Open pushmebaby in xcode.

2.Right-click the resouces folder and select Add existing files ..., Select the APs. developer. Identity. Cer file downloaded earlier (figure 25 ).

3.In the applicationdelegate. M file, modify the following code (bold ):

-(ID) Init {

Self = [Super init];

If (self! = Nil ){

Self. devicetoken = @ "38c866dd bb323b39 ffa73487 5e157ee5 a85e0b7ce90d56e9 fe145bcc 6c2c594b ";

Self. payload = @"{\"APS\":{\"Alert\":\"Yougot a new message!\",\"Badge\": 5,\"Sound\":\"Beep.wav\"},\"Acme1\":\"Bar\",\"Acme2\": 42 }";

Self. Certificate = [[nsbundle mainbundle]

Pathforresource: @ "aps_developer_identity" oftype: @ "CER"];

}

Return self;

}

4.Press release + R to run the program. You will be asked if you are allowed to use the certificate. Click Always allow (always allowed) (figure 26 ):

On the iPhone/iPod, make sure that the applepushnotification program is not running. Click the push button to send a push notification to the device. The server actually sends the following message to the APN Server:

{

"APs ":{

"Alert": "yougot a new message! ",

"Badge": 5,

"Sound": "beep.wav "},

"Acme1": "bar ",

"Acme2": 42

}

5.If the message is pushed successfully, it will appear on the iPhone/iPod (figure 27 ):

6.If you press notify + R to debug the applepushnotification program and then send a message from pushmebaby, the console displays the following output:

21:11:49. 182 applepushnotification [1461: 207] key: acme1, value: bar

21:11:49. 187 applepushnotification [1461: 207] key: APS, value :{

Alert = "you got a new message! ";

Badge = 5;

Sound = "beep.wav ";

}

21:11:49. 191 applepushnotification [1461: 207] key: acme2, value: 42

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.