Wednesday, 30 September 2015

APNs Push Notification - iOS

1. Using Apple Push Notification Service:

Apple Push Notification Service (APNs) is a service for iOS devices to send and receive push notification messages. You need an actual iDevices, like iPhone and iPad. Push notification is not supported on Simulators.
  1. An App requests iOS for push notification
  2. iOS sends the request to APNs
  3. APNs sends back a device token
  4. The Client app sends to your server with the device token.

To send a push notification:
  1. Ther server sends a payload to APNs with the token
  2. APNs sends a push notification to the device

Apple Push Notification Services (APNS) Overview
1.1. App ID Configurations and Certificates:

To develop and distribute your iOS app, you need to create an SSL certificate associated to an App ID and a provisioning profile.

This step is not going to be fun, but you must complete to be able to start developing for iOS.

1.2.Issuing a Certificate Signing Request:

To create an SSL certificate for a push notifications, first you need to generate a Certificate Signing Request (CSR).
  1. On your Mac, Open Keychain Access
  2. From the top menu, select Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority…
  3. Fill out your email address, common name
  4. Check Save to Disk
  5. Press Continue and save the .certSigningRequest file somewhere

apple01-csr
1.3 Creating an App ID:

You are going to create a unique App ID.
  1. On web browser, Apple Developer portal and navigate to Identifiers where you should see a list of your apps
  2. Click + Button at the top right to add a new app
  3. At Registering an App ID, enter the name of your app, enter an ID, such as com.yourdomain.pushApp (DO NOT select Wildcard App ID), check Push Notification
  4. Click Continue then Submit

apple02-appid







1.4 Configure Push Notifications for the App ID:

Once the APP ID registration is completed, you need to configure it to make to work with push notification.
  1. Select the App ID you just created, and click Edit
  2. At Push Notifications, Click Create Certificate then “Continue”
  3. Click Choose File…  and upload the .certSigningRequest file you have generated and saved on your Mac earlier. Click Generate.
  4. Once the certificate was generated, download it onto your Mac

apple03-edit



1.5 Create a Private Key:
Now you are going to create a private key from the downloaded certificate
  1. Double-Click the downloaded file. It should Opens in Keychain Access
  2. Select My Certificates at left. You should find the Certificate you just added
  3. Control-Click the Certificate, and select Export “Apple Development iOS Push Services...”
  4. Save it as .p12 file, by selecting File Format as Personal Information Exchange(.p12) in the Save as dialog

apple04-ssl-p12

1.6 Creating a Provisioning Profile:

  1. On Apple Developer Portal, go to Provisioning Profiles
  2. Click + to create a new provisioning file
  3. select iOS App Development, then Continue
  4. Select a correct App ID from the dropdown list, then Continue
  5. Select a correct certificate from the list, then Continue
  6. Select devices you are going to develop with, then Continue
  7. Enter a name for the provisioning profile, then Generate
  8. Download the file
  9. Double-click open the file in Xcode. The profile now should be added to Xcode.

apple05-provision

Note: The production certificate remains valid for a year, but you want to renew it before the year is over to ensure there is no downtime for your app

1.7 Making PEM file:
So now you have three files:
  • The CSR
  • The private key as a p12 file (PushChatKey.p12)
  • The SSL certificate, aps_development.cer


  • CSR file is use when your certificate expires, you can use Same to generate new one.
  • You have to convert the certificate and private key into a format that is more usable. Because the push part of our server will be written in PHP, you will combine the certificate and the private key into a single file that uses the PEM format.
Go to the folder where you downloaded the files, in my case the Desktop:
$ cd ~/Desktop/
Convert the .cer file into a .pem file:
$ openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem
Convert the private key’s .p12 file into a .pem file:
$ openssl pkcs12 -nocerts -out PushChatKey.pem -in PushChatKey.p12
Enter Import Password:
MAC verified OK
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
Note: if you don’t enter a PEM passphrase, openssl will not give an error message but the generated .pem file will not have the private key in it.

Finally, combine the certificate and key into a single .pem file:
$ cat PushChatCert.pem PushChatKey.pem > ck.pem
At this point it’s a good idea to test whether the certificate works. Execute the following command:
$ telnet gateway.sandbox.push.apple.com 2195
Trying 17.172.232.226...
Connected to gateway.sandbox.push-apple.com.akadns.net.
Escape character is '^]'.
Note: If you see the above response, then your Mac can reach APNS. Press Ctrl+C to close the connection. If you get an error message, then make sure your firewall allows outgoing connections on port 2195.
Let’s try connecting again, this time using our SSL certificate and private key to set up a secure connection:
$ openssl s_client -connect gateway.sandbox.push.apple.com:2195
   -cert PushChatCert.pem -key PushChatKey.pem
Enter pass phrase for PushChatKey.pem:
You should see a whole bunch of output, which is openssl letting you know what is going on under the hood.
Note :If the connection is successful, you should be able to type a few characters. When you press enter, the server should disconnect.



2. Develop iOS App with Cordova:

First, Create a project using Cordova CLI.

$ cordova create push-notify com.example.push PushNotification


$ cd push-notify


$ cordova platform add ios

2.1 Install Cordova Push Plugin:

Cordova Push Plugin allows your application to receive push notifications on Android, as well as Amazon Fire OS, iOS, Windows Phone and Windows 8 devices. The plugin can be automatically installed via the Cordova CLI:

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

2.1 Using APNs with Cordova:

Using the below given code you can  register your  device  as well as listen to  the APNs.

var pushNotification = window.plugins.pushNotification;
pushNotification.register(
   tokenHandler,
   errorHandler,
   {
      'badge':'false',
      'sound':'false',
      'alert':'true',
      'ecb':'onNotificationAPN'
   }
);


Listen to the callback Function.  The Response  will occur in  JSON format.
To support both Android (GCM) and iOS (APNs), install a Cordova Device plugin:

$cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git

and separate each platform, using device.platform API method:

// You must install Cordova Device Plugin to be able to use the method
if(device.platform == 'iOS')
{
// call the registration function for iOS
} else if (device.platform == 'Android' || device.platform == 'amazon-fireos')
{
// Android
}

if  anyone request to the server the e.event will occur everytime with ‘message’.

function onNotificationAPN(e)
{
   switch(e.event)
   {
      case 'message': if (e.foreground)
          // When the app is running foreground.
        // and Your Notification Code will be HERE.
          alert('You can print your message.')
      break;   
      case 'error':
          console.log('Error: ' + e.msg);
      break;   
      default: console.log('An unknown event was received'); break;
   }
}


When tokenHandler callback is called, you should successfully be able to obtain the device token.

function tokenHandler (result)
{
   console.log('device token: '+ result);
   // This is a device token you will need later to send a push
   // Store this to PubNub to make your life easier :-)
}

The token should look something like: 24c99cd5c39b283c58b554509c999999937aadb7b4bxxx0043cb363af6…



3.1 Send Request to the APNs:

and unzip it. You need to make some changes to simplepush.php.
// Put your device token here (without spaces):
$deviceToken = '0f744707bebcf74f9b7c25d48e3358945f6aa01da5ddb387462c7eaf61bbad78';

// Put your private key's passphrase here:
$passphrase = 'pushchat';

// Put your alert message here:
$message = 'My first push notification!';

Copy your ck.pem file into the SimplePush folder. Remember, the ck.pem file contains both your certificate and the private key.
Then open a Terminal and type:
$ php simplepush.php
If all goes well, the script should say:
Connected to APNS
Message successfully delivered
And within a few seconds you should receive your first push notification:Learn how to add Push Notifications into your iPhone app!
Thankful to www.pubnub.com

Tuesday, 29 September 2015

GCM Push Notification - Cordova

1. Using Google Cloud Messaging (GCM) :

Google Cloud Messaging(GCM) is a service for android devices to send and receive Android push notification messages.

To register a device:
  1. An Android device sends a Sender ID to GCM server
  2. GCM server sends back the Registration ID to the device
  3. You need to store Registration ID at your Server. Because You going to  need this to send request to GCM.

To send a push notification:
     4. Your Server send a request to GCM with the Registration ID
     5. GCM sends a push notification to the device.


http://intoitgames.com/blog/wp-content/uploads/2014/02/push-notification-gcm-apns-diagram-featured.png
How Google Cloud Messaging(GCM) works


1.1. Setting up Your Google Project :

To enable GCM service, you must configure in Google Developer Console.
  1. Go to Google Developer Console at cloud.google.com/console
  2. Create a Project
  3. On Project Dashboard, click Enable API button
  4. Turn on Google Cloud Messaging for Android

Enable-Google-Cloud-Messaging
1.2. Getting Your API Key :

Also, you will need your API key to be able to use the service.
  1. From the Dashboard,  select Credentials
  2. Under Public API Access, Click Create new key
  3. Select Server Key.
  4. click Create.

1.3. Getting Your Sender ID :

Copy the Project Number, which you should find on the top of the Project Dashboard. This is your GCM Sender ID you will need to enter in your Cordova app later. Finally, you are ready to use Android push notifications!

2. Develop Android App with Cordova:

First, Create a project using Cordova CLI.

$ cordova create push-notify com.example.push PushNotification


$ cd push-notify


$ cordova platform add android

2.1 Install Cordova Push Plugin:

Cordova Push Plugin allows your application to receive push notifications on Android, as well as Amazon Fire OS, iOS, Windows Phone and Windows 8 devices. The plugin can be automatically installed via the Cordova CLI:

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

2.2 Using GCM with Cordova:

Using the below given code you can  register your  device  as well as listen to  the GCM. Add the below given code in deviceready method of addEventListener.

var pushNotification = window.plugins.pushNotification;   
pushNotification.register(
successHandler,
errorHandler,
{
   'senderID':'your_sender_id',
   'ecb':'onNotificationGCM' // callback function
}
);

Listen to the callback Function.  The Response  will occur in  JSON format
so first time e.evet will occur with  ‘registered’ and if  anyone request to the server the e.evet will occur everytime with ‘message’.

function onNotificationGCM(e)
{
   switch(e.event)
   {
      case 'registered': if (e.regid.length > 0)
           alert(e.regid);
      break;
      case 'message': if (e.foreground)
          // When the app is running foreground.
        // and Your Notification Code will be HERE.
          alert('You can print your message.')
      break;   
      case 'error':
          console.log('Error: ' + e.msg);
      break;   
      default: console.log('An unknown event was received'); break;
   }
}

Below given function will return success for error with respect to the register method.

function successHandler(result) {
alert("Success : " +result);              
           console.log('Success: '+ result);
}


function errorHandler(error) {
           alert("Error : " +result);
           console.log('Error: '+ error);
}           

2.3 Send Request to the GCM:

To send request to  server you require  API-KEY, RegistrationID, and Message.
for the Testing purpose you can use  http://gcm-alert.appspot.com/
to send request to GCM. with URL as : https://android.googleapis.com/gcm/send

That's it!