Tuesday, April 25, 2017

Cordova Push Notification Using Firebase & Onesignal Plugin



What is Push Notification


Push notification is one of the best way to send messages to app user and its simplest way to reach to the app user. Push notification is message that pops out on mobile device. App publisher can send then at any time. Push notification is similar to SMS  text message but they only reach to users who have installed your app. Push notification are mostly using for e.g promoting products and increase sales,improve customer experience and sports scores and news right on their lock screen.

How to setup push notification in cordova with firebase using onesignal plugin. 

Firebase Setup Steps :-

  1.  First you have to create project in firebase so goto this link https://console.firebase.google.com login with your gmail account.
  2. Once login into your dashboard create new project by clicking on Add Project (+) sign.
  3. Then just entered project name and select country and created a project.
  4. After creating project just clicking on setting icon which near to overview menu which is in top-left corner then goto project settings
  5. Once you are in setting option select "Cloud Messaging" tab then go and copy the Legacy server key and below Sender ID
  6.  then stop here and start configuring your one signal for sending push notification for your app
One signal Setup Steps:




  1. login into one signal with gmail or facebook as per your choice.
  2. once login create a new app by clicking add new app (+) sign.
  3.  Once click on it enter app name once created goto to and click on  "All Apps" menu option which is on bottom-left corner .
  4. then you can see your app dashboard click on "Finish App Setup" after your clicking one it one pop will be open in that pop you have to select one platform to configure  so here we are using firebase so will be select "GCM" option.
  5. Once selected click on next then you have to copy and paste your "google server key " and "google project number" that you created in previous in firebase
  6. Once copy and paste proper server key and project number save it.
  7. after saving next pop will open and you have to select SDK so here i am choosing "Phonegap cordova" option.
     
  8. Once selected the sdk and after saving it you will get App ID is copy and paste in somewhere so that you have to used in onesignal plugin code.
Once configured firebase and onesignal open your cordova project and install onesignal plugin by using following command 

C:\Users\sushant\sampleX>cordova plugin add onesignal-cordova-plugin

copy below code into device ready function and copy and paste your App id which you already get singalong configuration previously 

onDeviceReady: function() {

    this.receivedEvent('deviceready');

    var notificationOpenedCallback = function(jsonData) {
        console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
      };

      window.plugins.OneSignal
        .startInit("3990f7d2-7608-4043-b9ad-9e79f299ceb2")
        .handleNotificationOpened(notificationOpenedCallback)
        .endInit();


     var onSuccess = function(position) {
             window.localStorage.setItem('long',position.coords.longitude);
             window.localStorage.setItem('lat',position.coords.latitude);
        };
        function onError(error) {
            alert('code: '    + error.code    + '\n' +
                'message: ' + error.message + '\n');
        }
     navigator.geolocation.getCurrentPosition(onSuccess, onError);
 }

Then run your app and then goto onesingal dashboard to send your push notification message to
your device

1. Select your app in one signal dashboard once clicked you see more option just select "New Push Notification"
2. next there are many option right now i am selecting "send to everyone"; -> next
3. Enter message title and message ->next
4.just click again next
5.then click on confim ->send message

   

Friday, April 7, 2017

Cordova App with Google Places Api Service


  1. In this we learn how to consume google place api service and create nearby place app using cordova. In this app we will fetch nearest Bank ATM List.
  2. In this app i will tell you what you will required which are as follows:- 
    1.  You required Google Place api key which you will get from below link-      https://developers.google.com/places/web-service/intro (Detailed Google Places api documentation) .
    2. Once you will get key just save or copy paste somewhere in txt file
    3. Now create project in cordova 
    4. Once cordova project is created goto project folder and install GeoLocation plugin in cordova project. with this plugin we will get current latitude and longitude Link for downloading plugin - cordova plugin add cordova-plugin-geolocation     
    5. Include jquery-1.11.1.min.js path in index.html
    6. Comment <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;"> line in index,html
    7. Open project in android studio.
    8. All above step completed then we will start for coding.
  3. So now open Index.js file in onDeviceReady we will write code for getting current position i.e longitude & latitude code is below
           var onSuccess = function(position) {
window.localStorage.setItem('long',position.coords.longitude);
window.localStorage.setItem('lat',position.coords.latitude);
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
From above code we will get longitude and latitude and we will be store that thing in our Localstore its one of the great feature of HTML5 where we can store value in key->value pair and used it anywhere in our code. for more information on localstore used this link below link https://www.w3schools.com/html/html5_webstorage.asp
4. Now write code for getting nearest bank ATM list in JQuery AJAX.
$(document).ready(function(){
    var lat=window.localStorage.getItem('lat');
    var long=window.localStorage.getItem('long');
    var radius=1;  // location radius which from 1 to 50000 km
    var type='atm'; // this a type which defined in google place service api
     $.ajax({
           type       : "POST",
           url        : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+lat+","+long+"
&radius="+radius+"000&type="+type+"&key=***insert key code here***", crossDomain: true, dataType : 'json', success : function(response) {
            //console.log(response.results) // check your response in console
            $.each( response.results, function(key,value ) {
                        $('.content').append('<li>'+value.name +''+'</li>');
            });
            },
            error: function() {
             alert('Something went wrong :(');
             }
            });
        })

       In above code i will get lat and long from local storage which already get its value using 
       Geolocation Plugin onDeviecReady Function and getting value from response.results obaject 
       we are using $.each function for getting value from object.
5. In Index.html write below code in body
<h4>Nearest ATM Bank List</h4>
         <ul class="content">
         </ul>
     In this li tag is created dynamically and will append that li to ul using jquey append function.

  6. Output of the code  & GitHub link for project folder  are below: 
   
          GitHub Link Click Here :)
         

Cordova Push Notification Using Firebase & Onesignal Plugin

What is Push Notification Push notification is one of the best way to send messages to app user and its simplest way to reach to the a...