21 August 2012
Additional required other products
Intermediate
The Apple Push Notification service (APNs) enables third-party application servers to send notifications to Apple iOS devices. You can leverage this ability when developing apps for devices running iOS. In this article, you'll learn how iOS push notifications work and how to implement them.
Apple supports three types of remote notifications that you can add to your projects: alerts (see Figure 1), badges (see Figure 2), and sounds.


The workflow for registering push notifications with a server-side service involves the following steps (see Figure 3):

Notifications are received by the client application using this process (see Figure 4):

Adobe AIR 3.4 provides push notification APIs you can use with APNs to subscribe and receive all three types of push notifications in AIR iOS apps.
The release of Adobe AIR 3.4 introduces a new set of APIs that are used for push notifications. They are listed below:
ALERT , BADGE, and SOUND . subscribe(options:RemoteNotifierSubscribeOptions = null):void unsubscribe():voidflash.notifications.RemoteNotifier in response to push notification events from APNs.Note: The status event dispatched by flash.notifications.RemoteNotifier is of the type flash.events.StatusEvent.
If you have experience developing with ActionScript, you'll likely find that the process of using the new push notifications in AIR iOS is familiar and fairly straight-forward. This list outlines the basic steps required:
The following code samples provide snippets of the ActionScript you'll use to subscribe to push notifications. All of the code is provided in the TestPushNotifications.as file located in the sample files folder.
The subscription steps are described in more detail below:
flash.notifications.NotificationStyleflash.notifications.RemoteNotifierflash.notifications.RemoteNotifierSubscribeOptionsflash.events.RemoteNotificationEventflash.events.StatusEventBefore subscribing to push notifications, add code to check that the device can receive push notifications.
private var remoteNot:RemoteNotifier = new RemoteNotifier();
private var tt:TextField = new TextField();
this.stage.addEventListener(Event.ACTIVATE,activateHandler);
public function activateHandler(e:Event):void{
if(RemoteNotifier.supportedNotificationStyles.toString() != " ") {
trace(“push notifications supported”);
}
else{
tt.appendText("\n Remote Notifications not supported on this Platform !");
}
}
Your application can subscribe to any of the three styles of notifications available in iOS.
ALERT – Notification displays an alert box upon receiving a notification.BADGE - Notification updates the icon of the application with a number or image upon receiving a notification.SOUND - Notification plays a sound upon receiving a notification.You can specify which styles of notifications your application will subscribe to using the notificationStyles property of the RemoteNotifierSubscribeOptions class. The sample code shown below subscribes to all three styles of push notifications:
private var preferredStyles:Vector.<String> = new Vector.<String>();
private var subscribeOptions:RemoteNotifierSubscribeOptions = new RemoteNotifierSubscribeOptions();
preferredStyles.push(NotificationStyle.ALERT ,NotificationStyle.BADGE,NotificationStyle.SOUND );
subscribeOptions.notificationStyles= preferredStyles;
Once you have confirmed the user's device supports push notifications and you've specified the notifications styles you'd like your app to receive, you can subscribe to the notifications using this code:
private var remoteNot:RemoteNotifier = new RemoteNotifier();
private var tt:TextField = new TextField();
this.stage.addEventListener(Event.ACTIVATE,activateHandler);
public function activateHandler(e:Event):void{
if(RemoteNotifier.supportedNotificationStyles.toString() != " ") {
remoteNot.subscribe(subscribeOptions);
}
else{
tt.appendText("\n Remote Notifications not supported on this Platform !");
}
}
The tokenId is a 32-byte number that uniquely identifies the user's device. If the subscribe() request succeeds, a RemoteNotificationEvent.TOKEN event is received. This event object contains the tokenId returned from the APNs. You must retrieve the tokenId from the event object. The code below simply traces the tokenId .
remoteNot.addEventListener(RemoteNotificationEvent.TOKEN,tokenHandler);
public function tokenHandler(e:RemoteNotificationEvent):void{
trace("\nRemoteNotificationEvent type: "+e.type +"\ntokenID:\n"+ e.tokenId);
}
After you have received a tokenId from APNs and retrieved it from the event object, you need to send the tokenId to the remote notification provider you are using. The sample project described in this article uses Urban Airship as the remote notification provider. Urban Airship offers a readymade remote notification provider. When using this provider, you only need only to send your tokenId to it by adding the following code:
private var urlreq:URLRequest;
private var urlLoad:URLLoader = new URLLoader();
private var urlString:String;
remoteNot.addEventListener(RemoteNotificationEvent.TOKEN,tokenHandler);
public function tokenHandler(e:RemoteNotificationEvent):void {
urlString = new String("https://go.urbanairship.com/api/device_tokens/" + e.tokenId);
urlreq = new URLRequest(urlString);
urlreq.authenticate = true;
urlreq.method = URLRequestMethod.PUT;
URLRequestDefaults.setLoginCredentialsForHost("go.urbanairship.com","_Provide_Application Key","_Provide_Application Secret");
urlLoad.load(urlreq);
urlLoad.addEventListener(IOErrorEvent.IO_ERROR,iohandler);
urlLoad.addEventListener(Event.COMPLETE,compHandler);
urlLoad.addEventListener(HTTPStatusEvent.HTTP_STATUS,httpHandler);
}
Please refer to your remote service provider's documentation for additional information.
A notification typically comes with JSON-formatted data. You can optionally make use of that payload data in your app.
remoteNot.addEventListener(RemoteNotificationEvent.NOTIFICATION,notificationHandler);
public function notificationHandler(e:RemoteNotificationEvent):void{
tt.appendText("\nRemoteNotificationEvent type: " + e.type +"\nbubbles: "+ e.bubbles + "\ncancelable " +e.cancelable);
for (var x:String in e.data) {
tt.text += "\n"+ x + ": " + e.data[x];
}
}
If the subscription request fails, a StatusEvent.STATUS is dispatched with the level "error". This sample code simply traces the error.
remoteNot.addEventListener(StatusEvent.STATUS,statusHandler);
public function statusHandler(e:StatusEvent):void{
trace("event Level" + e.level +"\nevent code " + e.code + "\ne.currentTarget: " + e.currentTarget.toString());
}
If you need unsubscribe from push notfications at runtime, you can use the unsubscribe() method. Typically this is performed in response to a user request to unsubscribe. In the sample code, the application includes a button allowing the user to choose to unsubscribe from notifications.
private var unSubsButton:CustomButton = new CustomButton("UnSubscribe");
unSubsButton.addEventListener(MouseEvent.CLICK,unSubsButtonHandler);
public function unSubsButtonHandler(e:MouseEvent):void {
remoteNot.unsubscribe();
tt.text +="\n UNSUBSCRIBED";
}
Note: Apple recommends that each time an app activates it should subscribe to the push notifications.
Entitlements allow applications to access special resources and capabilities on iOS. Push notifications require entitlements to use both the development and production certificates and profiles you will create later. You specify those entitlements in the Entitlements tag in the iPhone specific section of the application descriptor file. The iOS push notification entitlement key is aps-environment and is assigned a value of development or production as appropriate.
<iPhone>
<InfoAdditions>
…
</InfoAdditions>
<Entitlements>
<![CDATA[
<key>aps-environment</key>
<string>development</string>
]]>
</Entitlements>
</iPhone>
When you are finished and you're ready to publish your app on the App Store, add this line:
<string>production</string>
To enable your app to communicate with the APNs you must package it with the provisioning profile and a certificate that enables the iOS Push Services. The process of creating such a provisioning profile is explained in Local and Push Notification Programming Guide provided in the Apple iOS Developer Library. Pay close attention to the steps in the Provisioning and Development section to ensure you enable push notification services in your profile and create the proper SSL Certificate Keys. Note that there are two types of Push SSL certificates, one for development (testing purposes) and one for production. You will need to create both types. Keep both of the SSL certificates. Later in the process, you'll use them to enable app and provider communication.
You'll need a remote notification provider to send the push notifications to your app. The remote notification provider communicates with APNs to send push notifications to the client iOS app.
You can set up a PHP server using the Google ApnsPHP Apple Push Notification service. This Google Code project lets design you an interface to match your requirements. An example of the type of UI you can create is shown in Figure 5.

Alternatively, you can use a pre-existing remote notification provider. The sample project described in this article uses a provider named Urban Airship. To send notifications, you simply provide the device token and parameters (see Figure 6).

The .pem file contains the private key required for the SSL certificates. When you create a new app at the remote service provider, you will need the .pem file of the SSL certificate used for your app, which APNs will use to authenticate the provider. This section describes how to set up certificates to communicate between the application and the remote notification provider.
openssl x509 –in aps_developer_identity.cer –inform der –out TestPushDev.pemopenssl pkcs12 –nocerts –out TestPushPrivateKey.pem –in certificates.p12cat TestPushDev.pem TestPushPrivateKey.pem > FinalTestPush.pemWhen you create a new application in Urban Airship, it will ask for the Apple Push Certificate. When prompted, provide the combined .pem file.
Note: If you're setting up your own notification provider, you'll add code that uses the combined .pem file for authentication.
You can specify that a custom sound is played when a notification for your application is received. To add sounds, the sound files must be bundled with the application in same directory that contains the SWF and application.xml files. Custom alert sounds must be less than 30 seconds long—If you attempt to add a longer sound, iOS will play the default system sound instead.
iOS supports the following sound data formats:
The sound files can be packaged in AIFF, WAV, or CAF files.
This is an example packaging command:
Build/adt –package –target ipa-app-store –provisioning-profile _-_.mobileprovision –storetype pkcs12 –keystore _-_.p12 test.ipa test-app.xml test.swf sound.caf sound1.caf
If you want to use localized alert notifications for your app, you can bundle localized strings with the app in a lproj folder. For example, if you want to add the alert in French language, follow these steps:
"PokeMessageFormat" = "Test ce fichier sur %@ ";In the line of code shown above, PokeMessageFormat is the key of the alert. Test ce fichier sur is the message string.
To use localized strings in your app, you must include a supportedLanguages tag in your application descriptor file outside of the intialWindow tag. The sample application descriptor file (TestPushNotifications-app.xml) includes this line:
<supportedLanguages>en fr</supportedLanguages>After setting this up, when the app receives an alert notification with this key value, (and the language of the device is French), an alert displays on the device as shown in Figure 7:

When a user installs and launches the push notification-enabled app for the first time, the app displays a notification message (see Figure 8).

If the user clicks OK, the app can receive any of the three types of notifications to which it has subscribed. If the user clicks Don't Allow, then the device will not receive the notifications.
Once the user accepts, when your app is in the background (whether it is running or not) and it receives a notification, iOS will display an alert for your app (see Figure 09).

If your app is not receiving push notifications, open the Settings and check the phone's Notifications settings (see Figure 10).

In Figure 10, the app named TestPushNotifications has subscribed to all three types of notifications: Badges, Alerts, and Sounds.
Click the name of an app to access the individual notification settings (see Figure 11).

By adjusting the notification settings, users can turn off any style of notification. When notifications are disabled in the settings, your app will not receive the notifications—even though it is subscribed for that type of notification.
Hopefully this article has inspired you to add push notifications when developing apps for iOS devices. Once you get things set up, notifications can increase the functionality of the mobile projects you build. To learn more about developing iOS apps, see the following online resources:
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.