Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change.Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.

Additional required other products

User level

Sample files

In this article, I will explain how to set up and use Apple Push Notifications (APNs) in your PhoneGap mobile applications. Push notifications are different than local notifications in that they come from a third-party server to inform the user of something, versus a local notification which is scheduled by the application and run on the device itself without any server interaction.

For instance you may receive a push notification from Facebook notifying you that someone has added you as a friend, or if you are a Words With Friends player, you may receive a push notification indicating it’s your turn to play. An example of a local notification would be an alert popping up at a certain time or at an interval as a reminder from a to-do application where you set a date/time for a task; the alert pops up to remind you at that specified time. To end users, both notifications may appear the same in that they both pop alerts that can have sounds associated and other features, but they are very different from a development perspective.

There are Cordova/PhoneGap plugins to do both local and push notifications for iOS, but this series will focus on how to develop for push notifications. If you’re wondering about developing push notifications for Android, there is a concept of push notifications, but the setup and process is a bit different and will be covered in a separate article.

The process to get started with setting up APNs can be a bit intimidating initially but it’s worth taking the time to do so as the use cases are endless. This article is intended to help you understand the whole process including setup and what occurs on the application and server-side, with sample code to get you started quickly.

Explanation of the APN workflow

To start, it’s best to understand the workflow of Apple Push Notifications (APNs).

The following is a general overview for what you do to enable your app for push notifications. First, your application needs to be enabled for push notifications through the Apple iOS Provisioning Portal through an App ID (com.mysite.myapp) and signed with a provisioning profile that includes the push-enabled application identifier. Next, you also need to associate the App ID with an SSL certificate for communicating securely with Apple’s Push Notification Server. When you configure the App ID through the portal, a wizard will prompt you to create an SSL certificate that will be associated with your App ID and used for that purpose. Having the association with the App ID ensures that the notifications sent from your server to Apple’s APN Server only sends to the application with the matching id.

Once the certificate process completes, download a new provisioning file for this new App ID that contains the enabled push notifications. You then drag it into XCode and make sure it is the provisioning profile that is selected for your application in the Code Signing screen (under “Build Settings” for your project).

Setting up your application

This article assumes you know how to create a project including PhoneGap/Cordova, if not, please refer to the Getting Started with iOS section on the PhoneGap/Cordova website). Now that you’re ready to start coding your HTML/JavaScript/PhoneGap application, let’s go through the following steps to set it up.

The Cordova PushNotification plugin gives you a nice JavaScript API that you can use from your HTML/JS files to interact with the underlying native code to handle the registration and receive push notifications. Some of the functions provided are as follows:

registerDevice()

setApplicationIconBadgeNumber()

getRemoteNotificationStatus()

getPendingNotifications()

To use the JavaScript API, though, you first need to add some things to the native application code to bridge to the specific push notification code. The AppDelegate class for an application (located under your project Classes folder) implements the handlers for application-wide events, such as application launch, termination, and more. There are also events available for handling notifications. A list of them can be found in the Handling Notifications reference.

These methods are not implemented by default, however, so in order to support them you must add the code handlers and have them delegate to the included PushNotification.m class in the plugin code. The code to add is shown in the README file for the plugin, but we discuss it here as well. You are basically handling three events:

didReceiveRemoteNotification

didRegisterForRemoteNotificationsWithDeviceToken

didFailToRegisterForRemoteNotificationsWithError

Add the following code block to your AppDelegate.m class before the @endto handle the notification events:

The above code essentially creates a reference to the PushNotification class. It sets or reads some values and calls different methods with parameters depending on the event that occurred. Don’t worry if you don’t know any Objective-C or this seems complicated at this point, I have included the sample project that you can downloaded in the Requirements section for reference.

Finally, add a code fragment into the didFinishLaunchingWithOptions method in that same AppDelegate.m class to handle opening the application from a notification (and adding the received object to the pendingNotifications for later retrieval). Add this block right before the end return YES, as follows:

PushNotification plugin – JavaScript APIs

Now that you have the project setup complete including the native Objective-C handlers above, you can actually start coding with the Cordova PushNotification JavaScript interfaces. Below is further detail about some of them and examples of interacting with them in your code. There are others that are available that are not covered specifically in this article.

Register device

The PhoneGap PushNotification plugin offers a registerDevice() API to register your application with Apple’s Push Notification Service to receive push notifications. In the function, you specify exactly which types of notifications are enabled (alerts/badges/sounds). The result is a unique device token that the server-side can use to send the notification to that device. Apple recommends that you register your application for push notifications on the device every time it runs, since tokens can change.

An example of using the registerDevice() function is included in the sample project that you can download at the beginning of this article in the Requirement section. I show the code below:

Once the above code is in place and your application runs, you will receive an alert shown in Figure 4 asking the user whether he or she would like to receive push notifications (clicking “OK” or “Don’t Allow” results in a setting that can be modified in the user’s device settings as needed).

Figure 4. Prompt asking permission to send push notifications.

Get pending notifications

Pending notifications are those notifications that are received while the application was not active. When the application launches, retrieve them so that you can handle the data and send it as needed. The getPendingNotifications() function is available in the API for that purpose. See the example code below:

Set badge number

The badge number indicates pending notifications for a particular application through a number displayed in the upper-right-hand corner of the application icon. You will likely need to set the badge number on the application icon as you process the notifications. For instance if you open from a push notification you just received, you may want to decrease or clear it. Setting the badge number to zero will remove or clear the badge as shown below.

Anatomy of an Apple Push Notification

The maximum size for a notification payload is 256 bytes. If that limit is exceeded, it will be refused. Also note the delivery of notifications is “best effort” and not guaranteed, according to the Apple documentation, so you should not use it for sending critical or sensitive data, only to notify whether new data is available.

The notification payload is a JSON dictionary object that needs to contain another dictionary identified by the key aps. Then, the aps dictionary will contain one or more properties that specifies an alert to display, a badge number to set on the application icon, and/or a sound to play when the notification occurs. It’s also possible to create a custom payload but that is beyond the scope of this article. The alert object itself can contain just a string of text to display or a dictionary object with keys for a body, custom action button text to display and a custom launch image that you can set. See specific details about the payload at the Apple Push Notification Service documentation.

Here’s an example of a simple payload in bytes:

Figure 5. Anatomy of Apple Push Notifications.

A typical aps dictionary object contains three properties: alert, badge and sound. For example, let’s look at the following output:

Any custom sounds or launch images must be contained in the Resources folder in your project within XCode. For example in my image below, I have a notification-beep.wav and mysplash.png specified that I refer to in my push notification coming from the server.

Figure 6. Specifying custom sounds and images.

Server-side code handling

Below is example code that you could use to get started with a server-side solution to handle device token registration, which I currently call from my application sample to show how and at which point you might want to communicate with a third-party server to store device tokens after receiving the device token from Apple. Currently it doesn’t do anything with the token other than show that it and the message were received. The next step would be to store the users’s device token and any other information in a database for later use.

I simply run this script using Node.js on my localhost. When testing from your actual device (since push notifications are not supported in the emulator), you can set up a Manual HTTP Proxy in your device’s Wi-Fi settings to point to the IP Address of your computer. Go to your Wi-Fi network and scroll to the bottom of the settings to set the Manual Proxy server and port. Here’s an example of mine:

Figure 7. Testing on your device.

Sending a notification with Argon (Node.js API)

Below is an example of some simple code to show how you could use the argon open source Node.js API to send a push notification to a user’s device. I simply hard-coded my device tokens in for quick testing, but ultimately you would be retrieving them from a database to use for sending the push notifications.

The above code produces a notification that looks like the following on a device, assuming that you have your device Settings > Notifications > MyAppName set to the Alerts option:

Figure 8. Alert notification on your device.

If you’re device settings for Alert Style on the application is set to Banners, it will look like this:

Figure 9. Banner notification on your device.

Important note: You must change the PEM files to your cert and private key created in the setup (the ones you ultimately combined into a single PEM file with instructions in the SSL certificates and provisioning section. Remember you first converted the CER to a PEM, and then your .p12 to a PEM. Those are the two files that you need here. See the argon readme for more details on argon parameters). In my example, my PEM files are in the same folder as my Node.js code. You can omit the password property if you did not keep a password for them.