Monday 19 May 2014

Push Notification With Phonegap Part - 2

Hello Friends,

For more videos please this channel
http://youtube.com/WebBoostings
Please, Find the latest details about the Programming
http://webboostings.blogspot.in/
Visit our website
http://programming-guru.com/


Generating a new phonegap project


We will start by opening a new terminal window to generate a new phonegap application. If you dont have phonegap installed just start by doing this:

For more details you can use this link to create new project: Phonegap Configuration

Open your terminal and write this command.

$ npm install -g phonegap

This will install the phongap module globally

Navigate to the folder you want to generate the project:

$ cd your/project/path

Lets generate the project:

$ phonegap create PushNotificationApp --id "com.webconnect.webboostings" --name "PushNotificationApp"

Notice that you have 4 new directories in you project folder.

!important note: Use the same bundle id you used when you
created your application in the iOS developer center in the part 1 tutorial.
These ids are tied together when you export your Xcode project.

Then go to your newly created project:

$ cd PushNotification

Build the application for iOS:

$ Phonegap build ios

Install the PushPlugin from github via the phonegap CLI:

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

When you use the phonegap CLI to make a new
project,  it creates a kind of a dummy project for you. You can actually
export native apps to different platfoms  from this code as an example. We
don’t need this code so we are going to replace most of it.

Building our client

Replace this code with index.html

<!DOCTYPE html>
<html>
     <head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width,
       initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=0" />
     <link rel="stylesheet" href="css/main.css" />
     <title>Phonegap Push Notifications</title>
     </head>
<body>
    <div id="content">
        <h1>PushNotApp</h1>
        <h2>Push Notification:</h2>
        <p id="notification"></p>
   </div>
  <script src="phonegap.js"></script>
  <script src="js/plugins/PushNotification.js"></script>
  <script src="js/main-simple.js"></script>
</body>
</html>


Next you rename the index.css

*
{
    -webkit-tap-highlight-color:rgba(0,0,0,0);
    margin:0px;
    padding:0px;
}
body {
   -webkit-touch-callout: none;
   -webkit-text-size-adjust: none;
   -webkit-user-select: none;
   background-color: #e4e4e4;
   font-family: Helvetica, Arial, sans-serif;
   font-size:100%;
   height:100%;
   width:100%;
}

#content {
   margin-left: 10px;
}

Install the other plugins which helps us to display alert, console etc

First install the console plugin
so we can print console.log messages in Xcode.
$ phonegap local plugin add
https://git-wip-us.apache.org/repos/asf/cordova-plugin-console.git

Then install the device plugin so we
can get basic device information.
$ phonegap local plugin add
https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git

Last we install the local notification
and vibration api so we can display nice dialog boxes.
$ phonegap local plugin add
https://git-wip-us.apache.org/repos/asf/cordova-plugin-dialogs.git
$ phonegap local plugin add
https://git-wip-us.apache.org/repos/asf/cordova-plugin-vibration.git

Now, We have to paste this code in index.html page by using the script tag in the deviceready function.

var PushNotApp = PushNotApp || {};
PushNotApp.main = (function() {
var pushNotification = window.plugins.pushNotification,
showAlert = function(message, title)
  {
  if(navigator.notification) {
    navigator.notification.alert(message, null, title, 'Close');
    navigator.notification.vibrate(1000);
  }else{
    alert(title ? (title + ": " + message) : message);
  }
 },

addCallback = function(key, callback)
{
if(window.callbacks === undefined) {
    window.callbacks = {};
  }
  window.callbacks[key] = callback;
},

addNotification = function(notificationTxt) {
console.log('notification added to DOM');
  var el = document.getElementById('notification');
  el.innerHTML += notificationTxt;
},

registrationSuccessHandler = function(token) {
console.log('successful registration with token: ' + token);
addCallback('notificationHandler', notificationHandler);
},

registrationFailedHandler = function(error) {
  showAlert(error, "Error");
},

notificationHandler = function(evt) {
  console.log("received anotification: " + evt.alert);
  navigator.notification.beep(3);
  if(evt.alert) {
    addNotification(evt.alert);
  }
  if(evt.prop) {
    addNotification("received a special property: " + evt.prop);
  }
},

deviceReady = function() {
  console.log('Device is ready');
  if(parseFloat(device.version) === 7.0) {
  document.body.style.marginTop = "20px";
  }
  pushNotification.register(registrationSuccessHandler,
      registrationFailedHandler,
{
        "badge":"true",
            "sound":"true",
"alert":"true",
            "ecb":"callbacks.notificationHandler"
});
},

initialize = function() {
  document.addEventListener("deviceready",
deviceReady, false);
}
return
{
  initialize:initialize
}
}());
PushNotApp.main.initialize();


Now Build you app by Press cmd + b (window + b)

The anatomy of a Push Notification

For sending the push notification from server we have to follow the following structure.
{
"aps" : {
    "alert" : {
      "body" : "This is a push notification",
      "action-loc-key" : "Open",
      "launch-image" : "image.jpg"
    },
    "badge" : 1,
    "sound": "sound.aiff"
  },
  "key1" : "value1",
  "key2" : [ "value2", "value3" ]
}

Compiling your app in Xcode

Now it´s time to compile your application in Xcode so you can get your unique device token.

Navigate and open your exported
     Xcode project: YourAppFolder/platforms/ios/YourAppName.xcodeproj

Change the device to compile to.Chose your phone.

Run the application

Look in the output panel and you will see this:  successful registration with token: ” Your token string”

Copy your token, we are going to use it soon.


Building a simple NodeJS server

This is the last part of the tutorial and we
are going to build a simple NodeJS server that sends out a push notification to
your device. First you need to install an awesome node module that does all the
dirty work for us. I´m talking about the node-apn
module. The node-apn is basically a NodeJS module for interfacing with the
Apple Push Notification Service.  So in root of your project folder do this:

$ npm install apn
Now you have a node_modules folder that
contains the newly installed apn module. Do you remember the SSL certificate
and private key we exported form last tutorial? Well now its time to find them
and put your .pem files in a assets folder.  The last
step is to create a server.js file in root of our application:
In the Desktop folder create your new server.js file and paste this code into that file

var http = require('http');
var apn = require('apn');
var url = require('url');
var myPhone = "d2d8d2a652148a5cea89d827d23eee0d34447722a2e7defe72fe19d733697fb0";
var myDevice = new apn.Device(myPhone);
var note = new apn.Notification();
note.badge = 1;
note.sound = "notification-beep.wav";
note.alert= { "body" : "Your turn!", "action-loc-key" : "Play" , "launch-image" : "mysplash.png"};
note.payload = {'messageFrom': Webconnect};
note.device= myDevice;
var callback = function(errorNum, notification){
console.log('Error is: %s', errorNum);
console.log("Note" + notification);
}

var options = {
gateway:   'gateway.sandbox.push.apple.com', // this URL is different for Apple's
        Production Servers and changes when you go to production
    errorCallback: callback,
    cert: 'PushNotificationCer.pem',              
    key:  'PushNotificationKey.pem',              
    passphrase: ‘Certification Password',              
    port: 2195,                    
    enhanced: true,                
    cacheLength: 100              
}

var apnsConnection = new apn.Connection(options);
apnsConnection.sendNotification(note);


For sending the push notification on device please run this command
We have already compiled our
application in Xcode so all there is left to do is this to start the server:

$ node server.js
It will take some second and then you will get the owsome push


Notification on your device.



Message from Pushnotification



Push Notification With Phonegap Part - 1

Thank You
Abhishek Bendre

No comments:

Post a Comment