Add Facebook Login to your Ionic 3 App The Step-by-Step Guide 2019

Add Facebook Login to your Ionic 3 App The Step-by-Step Guide 2019
Facebook 


In this article, I'll tell you the best way to effortlessly execute the Facebook Login API into your delightful Ionic 3 application in only a couple of steps and lines of code. This guide is apprentices inviting, it implies that everybody who has some essential programming learning ought to have the option to comprehend and reproduce it.

Prior to beginning, I accept you as of now have Ionic 3 introduced on your PC. On the off chance that it's not the situation, you simply need to pursue this official instructional exercise on the most proficient method to set-up your condition.

1. Making the Ionic 3 App 


The absolute initial step of this instructional exercise will be to make an essential Ionic 3 application where we can later actualize the Facebook SDK and a login button. This part is finished utilizing the terminal to type some order lines — however in the event that you are a Windows client, you can skirt this section (1) and utilize Visual Studio Comminity rather which as of now contains every one of the instruments to kick you off.

We will make clear application so we are not diverted by a menu or a tab. To do this, simply execute this order :

ionic start fb-instructional exercise clear

At that point, execute this one to check whether everything is effectively set up :

ionic cordova serve

It ought to consequently dispatch your program with a page speaking to your application.

To complete with this part, simply open your recently made undertaking in your preferred code supervisor. I for one utilize Visual Studio Code which is anything but difficult to-utilize and works consummately with Ionic.

2. Making the Facebook App 


Incorporating Facebook Login requires the making of an application on the Facebook engineers stage.

Open the Facebook designers site and snap on "My Apps" > "Include a New App" on the upper right dropdown menu. When it is made, you will be diverted to your new application page.

Presently we have to add the stages we need to use with the Facebook SDK. Snap on the "Settings" menu connection and "Include Platform". Pick iOs or/and Android and glue your "Group ID" (for iOs) or "Google Play Package Name" for Android. This data can be found/altered at Line 2 in the "config.xml" record of your Ionic undertaking; for my situation :

<widget id="com.axelhardy.fbtutorial" version="0.0.1" xmlns="http://www.w3.org/ns/gadgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

At last, simply click on the "Dashboard" menu connection and duplicate your App Name and App ID. We will require these data sets for the stage 3.

3. Coordinating the Facebook SDK into your Ionic App 


Ionic makes it simple to introduce modules with only a couple of directions. Ensure you are still in your Ionic application index and execute this one :

ionic cordova module include cordova-module facebook4 - variable APP_ID="YOUR_APP_ID" - variable APP_NAME="YOUR_APP_NAME"

Supplant YOUR_APP_ID and YOUR_APP_NAME by the data sets your replicated to some extent 2.

At that point, introduce this recently included Cordova module :

npm introduce - spare @ionic-local/facebook

Well done! The Facebook module has been included and we would now be able to keep in touch with some code!

4. Composing the Code 


The principle some portion of our work will occur in the landing page which was naturally produced when we made the undertaking. The related documents are situated in "src/pages/home".

As a matter of course, when Ionic produces a page, it makes 3 records :

*.ts which contains the rationale/typescript (for the most part Javascript) code

*.html for the structure (HTML)

*.scss for the styles

We will begin by working just with the .html and .scss documents to plan something extremely basic.

So as a matter of first importance, open the "home.html" document and supplant the code by this one :

<ion-header>
    <ion-navbar>
        <ion-title>
            Facebook Tutorial
        </ion-title>
    </ion-navbar>
</ion-header>
<ion-content padding>
    <div class="intro">
        Tap the button below to log-in with Facebook
    </div>
    <div class="btn_container">
        <button ion-button full (click)="loginAction();">Login with Facebook</button>
    </div>
</ion-content> 

I have just added a simple text and a button with a click event :

(click)="loginAction();"

… which fundamentally implies that when this catch will be clicked, the loginAction() work that we will compose later in the typescript record will be executed.


To complete with the structure, open the home.scss record and glue the accompanying code :

page-home {
    .intro {
        text-align: center;
        border-bottom: 1px solid #e2e2e2;
        padding-bottom: 14px;
    }

    .btn_container {
        padding-top: 14px;

        button {
            background: #3b5998;
        }
    }
}

This should output the following result :
Add Facebook Login to your Ionic 3 App The Step-by-Step Guide 2019
Add Facebook Login to your Ionic 3 App The Step-by-Step Guide 2019

That is very straightforward yet that is the thing that we need :- ) ! 

Presently, we can at last compose the most significant code of this instructional exercise, the one which is identified with the Facebook API. 

Before opening the home.ts record — where the vast majority of the code will be composed — we have to incorporate the Facebook module we introduced in the section 2 into our venture. 

Open the document "src/application/app.module.ts" and include this line with different imports : 

import { Facebook } from '@ionic-local/facebook'; 

at that point, add the Facebook module to the rundown of suppliers :

providers: [
    StatusBar,
    SplashScreen,
    Facebook,
    { provide: ErrorHandler, useClass: IonicErrorHandler }

Presently that Facebook is added to our undertaking, open the document "src/pages/home.ts" so we can compose the loginAction() work. 

To utilize the Facebook API in our landing page, we have to import the module here as well. So simply include this import alongside different ones in the home.ts document :

import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook';

Then, we need to declare a variable in our constructor :

constructor(public navCtrl: NavController, public fb: Facebook) {}

What's more, presently, we can compose the loginAction() work which will be considered when a client taps on our catch from the home.html page. I will give you the whole code, and afterward, I will depict it in subtleties :

loginAction()
{
    // Login with permissions
    this.fb.login(['public_profile', 'user_photos', 'email', 'user_birthday'])
    .then( (res: FacebookLoginResponse) => {

        // The connection was successful
        if(res.status == "connected") {

            // Get user ID and Token
            var fb_id = res.authResponse.userID;
            var fb_token = res.authResponse.accessToken;

            // Get user infos from the API
            this.fb.api("/me?fields=name,gender,birthday,email", []).then((user) => {

                // Get the connected user details
                var gender    = user.gender;
                var birthday  = user.birthday;
                var name      = user.name;
                var email     = user.email;

                console.log("=== USER INFOS ===");
                console.log("Gender : " + gender);
                console.log("Birthday : " + birthday);
                console.log("Name : " + name);
                console.log("Email : " + email);

                // => Open user session and redirect to the next page

            });

        } 
        // An error occurred while loging-in
        else {

            console.log("An error occurred...");

        }

    })
    .catch((e) => {
        console.log('Error logging into Facebook', e);
    });
}

Line 4 : we utilize the login work from the Facebook API with a variety of authorizations. These consents will enable us to get specific informations about the clients. Note that a portion of these consents require to present your application to the survey group of Facebook.

For this situation, we will get the essential open informations (name or sex, for instance), an entrance to the photographs and collections, the email and the date of birth of the client.

Line 8 : a FacebookLoginResponse is come back with a status esteem. On the off chance that this worth is "associated", it implies that everything went well and the client is currently associated utilizing the Facebook API.

Line 11 and 12 : we get the ID and token that Facebook returned for us.

Line 15 : once associated, we would now be able to question the Facebook API to restore the data sets we need. All things considered, we are asking the name, sexual orientation, birthday and email for the as of now associated client.

Line 18 to 21 : if the inquiry was effective, we get an entrance to the data sets we mentioned about the client. We would now be able to utilize these informations to make a session in our application, and to divert the recently associated client to the landing page, or his dashboard, for instance.

Line 23 to 27 : we simply show the client's informations in the engineer's support.

To test your code, you totally need to utilize a genuine gadget or a test system (it won't work in program). Execute this order to do that :

ionic cordova run ios - gadget

Use ios/android relying upon your testing OS.

That is it! I trust you delighted in this bit by bit instructional exercise. The code of this total Ionic task is accessible on GitHub.

In the event that you need to go further, adapt increasingly Ionic tips or dispatch your own applications rapidly, I prepared some to-utilize and extremely complete Ionic 3 application source codes accessible on my site (https://stremmers.com).

Don't hesitate to utilize the remarks region on the off chance that you have a few inquiries, I will be glad to help or guide you.


Need all the more coding tips? Tail me on Medium :- ) !

Post a Comment

0 Comments