on Ionic, Parse and Facebook login

Standard

Totally newbies glossary:
1. Parse – Parse Server is an open source version of the Parse backend that can be deployed to any infrastructure that can run Node.js. Parse Server works with the Express web application framework. It can be added to existing web applications, or run by itself.
2. Ionic – Free and open source, Ionic offers a library of mobile-optimized HTML, CSS and JS components and tools for building highly interactive native and progressive web apps. Built with Sass, optimized for AngularJS.
3. Facebook – A privacy reseller 🙂

So the goal:
An android application, with Facebook login and Parse as a backend.

Step 1: Setting a Parse server.
You’ve probably heard, Facebook has decided to open source Parse server (and terminate it’s service).
Getting and running a local parse server is done with:

$ npm install -g parse-server mongodb-runner
$ mongodb-runner start
$ parse-server --appId APPLICATION_ID --masterKey MASTER_KEY

(you can replace the appId and masterKey to something more meaningful, should you want…)
But basically, that it. You’ve got a parse server up & running.
You can test it with sending a new POST request to save data:

curl -X POST \
-H "X-Parse-Application-Id: APPLICATION_ID" \
-H "Content-Type: application/json" \
-d '{"age":37,"patientName":"Sean Plott","illnessType":"Flu"}' \
http://localhost:1337/parse/classes/PatientCard

You will get a response with the object id and creation date.
(Ain’t that great?)

Step 2: Setting ionic application
Ionic is a wonderful framework for building hybrid mobile applications (e.g., use my beloved HTML, CSS and JavaScript to build a mobile app). Ionic is one of many hybrid frameworks, but I believe that (at least for both Android & iOS) it is the coolest and maturest.

From Ionic framework getting started, install ionic:

$ npm install -g cordova ionic

Once installed, start an empty ionic project:

$ ionic start myFacebookApp blank
  • You can create a blank, tabs, sidemenu apps

Once initialized, cd into the app and add Android / iOS by running:

$ ionic platform add android

/me cannot add ios on my Fedora, so added only android.

At this point you should also add Android (& iOS if using) environment. Easiest way would be to download Android Studio and SDK from Android developers website.

You can test your newly created app by running

$ ionic serve

this will open a browser tab with http://localhost:8100 (Keep this open, it will live reload with changes 🙂 ).

At this point I should remember to say that ionic relies heavily on AngularJS – that’s like its secret sauce.

Ionic’s directory structure:

The most important place is the ‘www’, this is where our hybrid app lives. The other “here be dragons” directories and files are the Android -> Cordova -> www connections and enablers (May cover those on a separate post).
So, the directory that will interest us most is the ‘www’ directory.
‘www’ directory is made of index.html (the entry point, eh?), css, img, js & lib directories. All of them are quite self-explanatory 😀

Step 3: Connecting Parse and Ionic

As we are building a JavaScript application, we need Parse’s JavaScript SDK.
I have cd’ed into www/js and downloaded latest Parse JavaScript SDK:

$ wget https://parse.com/downloads/javascript/parse-1.6.14.js -O parse.js

While talking about Parse JavaScript SDK, take a minute to look at their guides at https://parse.com/docs/js/guide

Now we have to tell ionic about Parse’s JavaScript. I have added it into my index.html (right above the <script src=”js/app.js”></script>:

<script src=”js/parse.js”></script>
<script>
Parse.initialize(“APPLICATION_ID”);
Parse.serverURL = ‘http://localhost:1337/parse/’;
</script>

So, the first part is adding the SDK. The second part is initializing Parse with my application id, and url (The url addition is since Parse can run anywhere this days…)

Next, I wanted to ensure that my ionic and parse play nicely.
I have followed a short tutorial from https://www.thepolyglotdeveloper.com/2015/04/use-parse-core-in-ionic-framework-mobile-apps/ — (note the changes in Parse initialize…)

Everything worked superb on my http://localhost:8100 and I have decided to give it a try on the Android emulator. I have ran:

$ ionic emulate android

It took some time to build and run, and once it was app running on the emulator. It didn’t work! 🙁
The app was trying to access http://localhost:1337, which it couldn’t.
So I had to change from Parse.serverURL = ‘http://localhost:1337/parse/’;
to Parse.serverURL = ‘http://10.0.2.2:1337/parse/’;
(On android emulator, 10.0.2.2 is a special alias to your host loopback interface).

That obviously broke my http://localhost:8100… so I went to Heroku for the help.
(which was easy as a click )

Now I have change the Parse.serverURL to the Heroku’s URL and it worked well on both the emulator and the browser.

Step 3 (Or 4 is it?): Facebook login

First, you’d have to create an app on Facebook. You should gain the APP_ID and APP_NAME

So, I’ve been smart and followed Parse’ excellent document on Users and Facebook login – https://parse.com/docs/js/guide#users-facebook-users

Yeah, well, that works only on the browser and does not work on the emulator (nor on the phone).

But as ionic is relayed on Cordova, we can use it to add Angular – Cordova integration with:

$ bower install ngCordova

this will install a set of tool to make Angular and Cordova play nicely together.
Next we need to update our index.html with the new ngCordova JavaScript files
(right below <script src=”cordova.js”></script>) so it looks like:

<script src="cordova.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
Next, we’d have to add Cordova’s facebook plugin. Usually you’d do it with “cordova plugin add pluginname”, alas I have learnt it may break the FacebookSDK (wat?)
To achieve that we’d go one directory up (above the www) and do:
$ git clone https://github.com/Wizcorp/phonegap-facebook-plugin.git
(this will download the plugin)

$ cordova -d plugin add phonegap-facebook-plugin \ 
--variable APP_ID="FB_APP_ID" --variable APP_NAME="FB_APP_NAME"

Where FB_APP_ID and FB_APP_NAME are the ID and Name of your Facebook app.

Now I have added a function to do the Facebook login. In my app.js it looks like:

$scope.FacebookLogin = function(){
  $cordovaFacebook.login(["public_profile", "email"]).then(function(success){
    var expiresIn = success.authResponse.expiresIn;
var expDate = new Date( new Date().getTime() + expiresIn * 1000).toISOString();
    varfacebookAuthData = {
      "id": success.authResponse.userID,
      "access_token": success.authResponse.accessToken,
      "expiration_date": expdate
    };
    Parse.FacebookUtils.logIn(facebookAuthData, {
      success: function(user) {
        console.log(user);
        if(!user.existed()) {
          alert("User signed up and logged in through Facebook!");
        } else{
          alert("User logged in through Facebook!");
        }
      },
      error: function(user, error) {
        alert("User cancelled the Facebook login or did not fully authorize.");
      }
    });
  }, function(error){
    console.log(error);
  });
};
This has been wired to on a new button:
<button class=”button” ng-click=”FacebookLogin()”>Login with Facebook</button>
And, voila! We have a working Facebook login on our little ionic app.

Leave a Reply

Your email address will not be published. Required fields are marked *