Cordova iOS push notification

Posted By : Roopesh Sharma | 03-Jun-2014

Cordova iOS push notification

Push Notification:

Push Notifications allow you to send notifications from a server directly to an iOS device. Push notification allows an app to notify you of new messages or events without the need to actually open the application, similar to how a text message will make a sound and pop up on our screen.

There are following tasks a push notification can do:

  • Display a short text message
  • Play a brief sound
  • Set a number in a badge on the app’s icon

How push notification works:

An app enables push notification on device. In this step user has to confirm that he/she want to receive notifications on device.

After it app receives a “device token”. This device token is used as the app’s user address in which user receive a notification from application server.

This device token is send to the server to register the device with the server for sending push notifications.

When something of interest to our app happens, the application server sends a push notification to the Apple Push Notification services(APNs).

Apple Push Notification services sends push notifications to our device.


Implementation of push notification in cordova:

To install plugin go to the application root folder and execute the following command in terminal:

cordova plugin add https://github.com/phonegap-build/PushPlugin.git

Add the PushNotification.js script to our www folder (or javascripts folder, wherever you want keep it) and reference it in our index.html file.

                
        

Required Certificate to push notification:

To implement iOS push notification we generate APPLE PUSH NOTIFICATION CERTIFICATE (.PEM FILE). To generate Apple Push Notification Certificate we required:

  • Certificate Signing Request (CSR) file
  • Private key file
  • SSL certificate

These are the following steps to generate APPLE PUSH NOTIFICATION CERTIFICATE:

Step1- Generating the Certificate Signing Request (CSR):

Open Keychain Access on your Mac and click on Keychain Access then click ‘Certificate Assistant’ choose the menu option ‘Request a Certificate from a certificate authority...’

KeyChainAccess

After that give the email address and common name to the certificate and select on saved to disk then click to continue..

certtificate_Assistant

and then saved it to hard disk.

certificate_Assistant_save

Step2- Export the private key: Go to the Keys section of Keychain Access, you will see that a new private key has appeared in your keychain. Right click it and choose Export.

Private_key

and then saved it to hard disk as PushManagerKey.p12.

Step3- Login to iOS Provisioning Portal, click "Certificates,Identifiers & Profile” on the left navigation bar. Then, click on “App IDs” in Identifiers , click ”+” button to create app id or if already created app id then select it. After click on ‘edit’ button and enable the push notification service for Development or Distribution.

Scroll down to the Push Notifications section and select the Create Certificate button in the Development SSL Certificate section.

 

Now, The “Add iOS Certificate” wizard comes up.

 

 

The first thing it asks you is to generate a Certificate Signing Request. We already generate Certificate Signing Request, so click Continue. In the next step we upload the Certificate Signing Request file. Choose the CSR file that we generated and click Generate. It takes a few seconds to generate the SSL certificate. Click continue if it’s done. Then download the certificate. It is named as ‘aps_development.cer’.

 

Step4- Open a terminal go to the folder where you saved these files:

Convert the .cer file into a .pem file:

              $ openssl x509 -in aps_development.cer  -out PushManagerCert.pem  
        

Convert the private key’s.p12 file into a .pem file:

               $ openssl pkcs12 -nocerts -out PushManagerKey.pem -in PushManagerKey.p12
	       Enter Import Password: ******
	       MAC verified OK ******
	       Enter PEM pass phrase: ******
	       Verifying - Enter PEM pass phrase: ****** 
        

And the last process is to combine certificate and key file to make a final certificate for server

              cat PushManagerCert.pem PushManagerKey.pem > CertificateKey.pem  
        

Note- The above CertificateKey.pem file is used by our application server along with password.

Handling of iOS push notification:

The plugin instance variable.

                var pushNotification;

                document.addEventListener("deviceready", function(){
                     pushNotification = window.plugins.pushNotification;
                     ...
                });
        

Register

Register to be called as soon as the device becomes ready.

                if ( device.platform == ‘iOS’){
                    pushNotification.register(
                    tokenHandler,
                    errorHandler,
                    {
                      "badge":"true",
                      "sound":"true",
                      "alert":"true",
                      "ecb":"onNotificationAPN"
                    });
                  }
        

tokenHandler

TokenHandler function called when the device has registered with a unique device token.

              function tokenHandler (result) {
                // Your iOS push server needs to know the token before it can push to this device
                // here is where you might want to send it the token for later use.
                alert('device token : ' + result);
              }  
        

errorHandler

ErrorHandler called when the plugin returns an error.

              function errorHandler (error) {
                  alert('error = ' + error);
              }  
        

Event callback that gets called when our device receives a notification:

              function onNotificationAPN (event) {
                  if ( event.alert ){
                      //Alert the text message
                      navigator.notification.alert(event.alert);
                  }

                  if ( event.sound ){
                      //Play the sound
                      var snd = new Media(event.sound);
                      snd.play();
                  }

                  if ( event.badge ){
                      //To show the badge number
                      pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
                  }

                  if (event.foreground==0){
                      //alert when application is not active
	              navigator.notification.alert(‘Application is cold start.’)
                  }
            }

        

Unregister

When a user exit our app then it is necessary to remove/invalidate current device token from server, we clean up our used resources and we call unregister() to free it. If we execute unregister(), the current device token is invalidate from the server, and next time we call register() to get a new device token.

                pushNotification.unregister(successHandler, errorHandler, options);
        

About Author

Author Image
Roopesh Sharma

Request for Proposal

Name is required

Comment is required

Sending message..