Requirements
Prerequisite knowledge
  • Previous experience working with ActionScript 3 and developing AIR iOS applications is required.
  • To follow along with this article, you need a membership in the Apple iOS Developer program and knowledge of the iOS development process.
  • You'll also need the associated security and configuration files necessary to build an iOS app. A Mac OSX computer is required to complete some parts of the iOS development process outlined in these instructions.
Required products
Flash Builder (Download trial)
Adobe Animate CC
Adobe AIR SDK
Additional required other products
User level
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.
 
Figure 1. Examples of alert notifications.
Figure 1. Examples of alert notifications.
 
Figure 2. An example of a badge notification.
Figure 2. An example of a badge notification.
 
The workflow for registering push notifications with a server-side service involves the following steps (see Figure 3):
 
  1. The client application requests iOS for push notifications.
  2. iOS forwards the request to the Apple Push Notification Service (APNs).
  3. The server returns a tokenId to iOS.
  4. iOS returns the tokenId to the client application.
  5. The client application provides the tokenId to the remote notification provider in order to receive push notifications.
Figure 3. A diagram illustrating how iOS apps register for push notifications.
Figure 3. A diagram illustrating how iOS apps register for push notifications.
 
Notifications are received by the client application using this process (see Figure 4):
 
  1. The remote notification provider generates a notification and then passes the notification payload to APNs.
  2. APNs forwards the notification to iOS on the device.
  3. iOS passes the notification payload to the application.
Figure 4. The process iOS apps use to receive push notifications.
Figure 4. The process iOS apps use to receive push notifications.
 
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.
 

 
Working with the ActionScript push notification API

The release of Adobe AIR 3.4 introduces a new set of APIs that are used for push notifications. They are listed below:
 
  • flash.Notifications.NotificationStyle defines the constants for notification types: ALERT , BADGE, and SOUND .
  • flash.notifications.RemoteNotifierSubscribeOptions enables you to select the styles of notifications that your app can receive.
    • notificationStyles:Vector.<String> specifies all of the notification styles that you want to register for the app.
  • flash.notifications.RemoteNotifier enables you to subscribe and unsubscribe from push notifications; it uses queries to identify which notification styles are supported on iOS and dispatch events.
    • supportedNotificationStyles : Vector.<String> A vector of all supported notification styles on the iOS platform.
    • subscribe(options:RemoteNotifierSubscribeOptions = null):void
    • unsubscribe():void
    • token – Event dispatched when a notification token is available upon successful subscription for remote notifications.
    • notification – Event dispatched in response to a new notification received by the application.
    • status – Event dispatched if an error is encountered during the subscription process.
  • flash.events.RemoteNotificationEvent contains the notification and token events that are dispatched by flash.notifications.RemoteNotifier in response to push notification events from APNs.
    • tokenId:String contains the tokenId received from APNs; the tokenID is used to identify the application.
    • data:Object contains data sent with the notification in JSON.
Note: The status event dispatched by flash.notifications.RemoteNotifier is of the type flash.events.StatusEvent.
 

 
Subscribing to push notifications using ActionScript

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:
 
  1. Import the necessary classes.
  2. Confirm the iOS device supports push notifications.
  3. Subscribe to notifications.
  4. Retrieve the tokenId.
  5. Send the tokenId to the remote notification provider.
  6. Work with notification data.
  7. Handle subscription failures.
  8. Unsubscribe from push notifications.
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:
 
 
Import the necessary classes
  • flash.notifications.NotificationStyle
  • flash.notifications.RemoteNotifier
  • flash.notifications.RemoteNotifierSubscribeOptions
  • flash.events.RemoteNotificationEvent
  • flash.events.StatusEvent
 
Confirm the iOS device supports push notifications
Before 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 !"); } }
 
Select the notification styles that your app will receive
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;
 
Subscribe to notifications
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 !"); } }
 
Retrieve the tokenId from APNs
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); }
 
Send the tokenId to the remote notification provider
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.
 
 
Work with notification data
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]; } }
 
Handle subscription failures
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()); }
 
Unsubscribe from push notifications
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.
 

 
Changing the application descriptor file (application.xml) to enable 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>

 
Creating SSL certificates and provisioning profiles with push notification services enabled

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.
 

 
Configuring a remote notification provider

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.
 
 
Set up your own APNs-php open-source server
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.
 
Figure 5. A remote provider interface created with Google ApnsPHP Apple Push Notification service.
Figure 5. A remote provider interface created with Google ApnsPHP Apple Push Notification service.
 
 
Use an existing remote notification provider
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).
 
Figure 6. Enter the notification information in the Urban Airship interface.
Figure 6. Enter the notification information in the Urban Airship interface.
 
 
Create .pem files from the SSL certificates
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.
 
  1. Create a .pem file from an SSL certificate by typing the following command in Terminal:
openssl x509 –in aps_developer_identity.cer –inform der –out TestPushDev.pem
  1. Create a .pem of the private key(.p12) by typing the following command:
openssl pkcs12 –nocerts –out TestPushPrivateKey.pem –in certificates.p12
  1. Combine the two. pem files into one .pem by typing the following command:
cat TestPushDev.pem TestPushPrivateKey.pem > FinalTestPush.pem
When 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.
 

 
Using custom sounds for push notifications

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:
 
  • Linear PCM
  • MA4 (IMA/ADPCM)
  • µLaw
  • aLaw
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

 
Using localized push alert notifications

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:
 
  1. Create a folder named fr.lproj that contains a Localizable.Strings file.
  2. In Localizable.Strings, provide the key of the alert and the message string in the language of phone, that looks something like this:
"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:
 
Figure 7. An example of a localized alert.
Figure 7. An example of a localized alert.
 

 
Accepting push notifications in an application

When a user installs and launches the push notification-enabled app for the first time, the app displays a notification message (see Figure 8).
 
Figure 8. A message prompts the user to accept push notifications.
Figure 8. A message prompts the user to accept push notifications.
 
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).
 
Figure 9. An example of an iOS alert notification.
Figure 9. An example of an iOS alert notification.
 

 
Troubleshooting your iOS application

If your app is not receiving push notifications, open the Settings and check the phone's Notifications settings (see Figure 10).
 
Figure 10. Check the notification settings on the iOS device.
Figure 10. Check the notification settings on the iOS device.
 
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).
 
Figure 11. You can enable or disable the application's notification settings on the device.
Figure 11. You can enable or disable the application's notification settings on the device.
 
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.
 

 
Where to go from here

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: