In this article I’ll explain how to setup push notifications with PhoneGap and iOS.

Prepare your PhoneGap app
First off, you have to install the Push Plugin for PhoneGap:
1 |
$ cordova plugin add https://github.com/phonegap-build/PushPlugin.git |
You also need the PhoneGap device plugin:
1 |
$ cordova plugin add org.apache.cordova.device |
Although not needed, for debugging purposes, it could also be handy to install the console-plugin for PhoneGap, so you can check your console.log -messages in XCode:
1 |
$ cordova plugin add org.apache.cordova.console |
The next thing you need to do, is copy the PushNotification.js -file to the www-folder of your app (or in a subdirectory in your app, whatever, your app just needs this file). Include this file in your apps’ index.html -file:
1 |
<script type="text/javascript" src="js/PushNotification.js"></script> |
Now we just need to add some JavaScript to allow our app to register the users’ device and to receive push notifications on it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// Setup push notifications: try { var pushNotification = window.plugins.pushNotification; if (window.device.platform == 'iOS') { // Register for IOS: pushNotification.register( pushSuccessHandler, pushErrorHandler, { "badge":"true", "sound":"true", "alert":"true", "ecb":"onNotificationAPNS" } ); } } catch(err) { // For this example, we'll fail silently ... console.log(err); } /** * Success handler for when connected to push server * @param result */ var pushSuccessHandler = function(result) { console.log(result); }; /** * Error handler for when not connected to push server * @param error */ var pushErrorHandler = function(error) { console.log(error); }; /** * Notification from Apple APNS * @param e */ var onNotificationAPNS = function(e) { // ... }; |
Setup your app within iOS Dev Center
Now this is the part that might scare you when your (like me) new to PhoneGap and/or app development for iOS: the jungle of certificates and provisioning profiles of Apple to get your app working. But don’t worry, I’ll try to explain step-by-step on how to tie it all together:
- Log in on Apple’s Developer Center.
- Go to ‘Certificates, Identifiers & Profiles’.
- If you haven’t already created an App ID, create it now and make sure to enable push notifications. Or edit your existing App ID and enable them.
- Click the ‘Create Certificate’ button and follow the instructions on screen.
- Download and install the certificates on your Mac.
- Make sure to create a certificate for development and for production.
- Create a provisioning profile for your app. Follow the instructions on screen.
- Install the provisioning profile on your Mac by double-clicking it.
- In Xcode, assign the correct provisioning profile for ‘Projects’ and ‘Targets’. You do this in the ‘Code Signing’-section.
- In OSX, open Keychain Access (if it isn’t open already) and navigate to the certificate you want to use for your push notifications.
- Right-click it, and export it as a P12 certificate. Use as name apns-dev-cert.p12 (in case of the development certificate).
- Expand the certificate and export the private key as a P12 certificate. Use as name apns-dev-key.p12 .
- Now open up your terminal to create a PEM-certficate out of these 2 certificates:
12$ openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12$ openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12 - To not have PHP prompt you for a password, either don’t provide a password when creating the P12 certficates, or do:
1$ openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem - Now concatenate these 2 files into 1 PEM-certificate:
1cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem
Now you have created a certificate that PHP can use to communicate with the APNS server. And the APNS server knows it’s cool because the PEM-certificate is created according to the certificates provided to you by Apple.
Setup your PHP Server
This example provides a simple example on how to setup a simple PHP server to send your push notifications to Apples’ APNS server. There are out-of-the-box solutions for this, but it’s also good to have a bare minimum example on how to achieve this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// Set parameters: $apnsHost = 'gateway.sandbox.push.apple.com'; $apnsPort = 2195; $apnsCert = 'apns-dev.pem'; // Setup stream: $streamContext = stream_context_create(); stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert); // Open connection: $apns = stream_socket_client( 'ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext ); // Get the device token (fetch from a database for example): $deviceToken = '...'; // Create the payload: $message = 'Hallo iOS'; // If message is too long, truncate it to stay within the max payload of 256 bytes. if (strlen($message) > 125) { $message = substr($message, 0, 125) . '...'; } $payload['aps'] = array('alert' => $message, 'badge' => 1, 'sound' => 'default'); $payload = json_encode($payload); // Send the message: $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload; fwrite($apns, $apnsMessage); // Close connection: @socket_close($apns); fclose($apns); |
That’s it! Now you are able to send push notifications from your PHP server to your iOS PhoneGap app.
Special thanks go out to David Mytton who has written an excellent article that helped my greatly setting up push notifications with PhoneGap and iOS. I also wrote a dutch translation of this article.
Visitors give this article an average rating of 3.9 out of 5.
How would you rate this article?
★ ★ ★ ★ ★
Thanks Giel for this article. Though I executed your tutorial with great attention I can’t succeed in having pushSuccessHandler and pushErrorHandlerboth functions executed, in fact I have no logs from them. The alert requesting for Push Notifications authorisation doesn’t even appear. I tested it on ios7 and push plugin version is 2.3.1. I hope someone can help.
Thanks
Is your server up and running and have you done the right actions with Apple to make use of the APNS service?
I forgot to tell that SSL connection works. I used only developer certificates, not distribution or production.
Did you add the APNS rights to your provisioning profile?
Yes, in my provisioning file I can read
Enabled Services: Push Notifications, In-App Purchase, Game Center
I didn’t use a server, thought the device registration to get tokenId doesn’t need my server
Hi Giel, Do you also have experience with adding push or other native functionality to an already existing responsive website? The idea is to leave the website as it is and just wrap it with cordova so we can use the native features. But i am not sure if the application will be approved by apple because it’s just a ‘wrapper’ for a online website. Hope you can help. Thanks!
Hi Brian,
Although I don’t have experience with what you are trying to achieve, I do recall heaving read somewhere that if your app is nothing more than a wrapper for a mobile website, the chances on rejection are like 99%. Which makes sense of course.
I think you need to rethink your business case and give the app a specific functionality that a mobile website can’t (although that line is also blurring every day). Bottom line: don’t create an app “’cause it’s cool to have an app in the App Store”. Because then you’re left with a crApp and in the worst case it’s only going to backfire resulting in a negative brand experience.
But that’s just my opinion. 😉
Hi Giel,
Thanks for the inspiration! Our solution will be:
– Rebuild the already existing codebase (desktop version) into a webapp
– Share the codebase with Cordova, wrap it and add push functionality
The advantage will be:
– Same user experience cross platform
– Same codebase
– Because most of the assets are installed with Cordova the application can work for 70% offline.
Hi Giel,
Thanks for your sharing. I need your help. I got pushSuccessHandler successfully. But i am not getting Push Notification from server side. I just copy past your sample php code in my server. I give my iPhone device token for testing. But nothing is happened. I don’t know why? Please help me.
Thank You !!!
Hi Arunkumar,
Do you have the *.pem setup correctly on the server?
It works!
thanks!
thank you, you save my day 🙂