WEB DEVELOPER SITE
TUTORIALS HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML


 

Ionic - Cordova Facebook


This plugin is employed for connecting to Facebook API. Before you begin desegregation Facebook, you would like to form a Facebook app here. you may produce an online app and so skip the fast begin screen. Then, you would like to feature the web site platform on the settings page. you'll use the subsequent code snip for the location universal resource locator whereas in development.

http://localhost:8100/

After that, you need to add Valid OAuth redirect URIs on the settings/advanced page. Just copy the following two URLs.

https://www.facebook.com/connect/login_success.html
http://localhost:8100/oauthcallback.html

Installing Facebook Plugin

We did all the steps higher than to tackle some problems that usually seem once victimization this plugin. This plugin is difficult to line up as a result of there area unit plenty of steps concerned and documentation does not cowl all of them. There are some better-known compatibility problems with alternative Cordova plugins, thus we'll use Teleric verified plugin version in our app. we'll begin by putting in browser platform to our app from the prompt.

C:\Users\Username\Desktop\MyApp>ionic platform add browser

Next, what we need to do is to add the root element on top of the body tag in index.html.

index.html

<div id = "fb-root"></div>

Now we will add Cordova Facebook plugin to our app. You need to change APP_ID and APP_NAME to match the Facebook app you created before.

C:\Users\Username\Desktop\MyApp>cordova -d plugin add 
   https://github.com/Telerik-Verified-Plugins/Facebook/ 
   --variable APP_ID = "123456789" --variable APP_NAME = "FbAppName"

Now open index.html and add the subsequent code once your body tag. once more you wish to create positive that the appId and version ar matching the Facebook app you created. this can make sure that Facebook SDK is loaded asynchronously while not obstruction the remainder of the app.

index.html

<script>
   window.fbAsyncInit = function() {
      FB.init({
         appId      : '123456789',
         xfbml      : true,
         version    : 'v2.4'
      });
   };

   (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

Angular Service

Since we installed everything, we need to create service that will be our connection to the Facebook. These things can be done with less code inside the controller, but we try to follow the best practices, so we will use Angular service. The following code shows the entire service. We will explain it later.

services.js

.service('Auth', function($q, $ionicLoading) {
   this.getLoginStatus = function() {
      var defer = $q.defer();
      
      FB.getLoginStatus(function(response) {
		   if (response.status === "connected") {
            console.log(JSON.stringify(response));
         } else {
            console.log("Not logged in");
         }
      });

      return defer.promise;
   }
   this.loginFacebook = function() {
      var defer = $q.defer();

      FB.login(function(response) {
		   if (response.status === "connected") {
            console.log(JSON.stringify(response));
         } else {
            console.log("Not logged in!");
         }
      });

      return defer.promise;
   }
   this.logoutFacebook = function() {
      var defer = $q.defer();

      FB.logout(function(response) {
         console.log('You are logged out!');
      });

      return defer.promise;
   }
   this.getFacebookApi = function() {
      var defer = $q.defer();

      FB.api("me/?fields = id,email", [], function(response) {
		
         if (response.error) {
            console.log(JSON.stringify(response.error));
         } else {
            console.log(JSON.stringify(response));
         }
      });

      return defer.promise;
   }
});

In the above service, we are creating four functions. First three are self-explanatory. The fourth function is used for connecting to Facebook graph API. It will return the id and email from the Facebook user.

We are creating promise objects to handle asynchronic JavaScript functions. Now we need to write our controller that will call those functions. We will call each function separately for better understanding, but you will probably need to mix some of them together to get the desired effect.

Controller Code

.controller('MyCtrl', function($scope, Auth, $ionicLoading) {
   
   $scope.checkLoginStatus = function() {
      getLoginUserStatus();
   }

   $scope.loginFacebook = function(userData) {
      loginFacebookUser();
   };

   $scope.facebookAPI = function() {
      getFacebookUserApi();
   }

   $scope.logoutFacebook = function() {
      logoutFacebookUser();
   };

   function loginFacebookUser() {
      return Auth.loginFacebook();
   }

   function logoutFacebookUser() {
      return Auth.logoutFacebook();
   }

   function getFacebookUserApi() {
      return Auth.getFacebookApi();
   }

   function getLoginUserStatus() {
      return Auth.getLoginStatus();
   }
})
You square measure most likely speculative why did not we have a tendency to came Auth service directly from the operate expressions (first four functions). the explanation for this is often that you simply can most likely wish to feature some additional behavior once the Auth operate is came. you may send some information to your info, modification the route once login, etc. this could be simply done by victimisation JavaScript then() technique to handle all the asynchronous operations rather than callbacks. Now we'd like to permit users to move with the app. Our markup language can contain four buttons for career the four functions we have a tendency to created.

HTML Code

<button class = "button" ng-click = "loginFacebook()">LOG IN</button>
<button class = "button" ng-click = "logoutFacebook()">LOG OUT</button>
<button class = "button" ng-click = "checkLoginStatus()">CHECK</button>
<button class = "button" ng-click = "facebookAPI()">API</button>

When the user taps the LOG IN button, the Facebook screen will appear. The user will be redirected to the app after the login is successful.

Ionic Cordova Facebook