loading...

Adding Facebook Login to your Ionic app (in 15 minutes)

fvaldes33 profile image Franco Valdes ・4 min read

So I tweeted this a few weeks ago and had a few requests for a quick write up.

So here it is...

In this quick tutorial we will cover installing the Ionic CLI, starting up an Ionic project, enabling Capacitor, installing the Facebook plugin and tie it all together with a few lines of code. Yes, just a few lines of code. I will write a separate post about integrating Firebase with your Ionic app as a part 2.

Ionic CLI & Ionic Starter App

Install the Ionic cli and start up a new application.

npm i -g ionic@latest

// ionic start [name] [template] [--type react|angular|vue]
ionic start facebook-login tabs --type angular

At this point you should be able to run ionic serve and see the boilerplate tab app ready for some code. We wont be writing anything yet, few more things to set up first.

Capacitor

Next up, Capacitor. Let's get our Ionic app and Capacitor talking. Here we will enable Capacitor through the Ionic CLI and then use npx to avoid installing any other global packages.

ionic integrations enable capacitor

// npx cap init [name] [appid]
npx cap init facebook-login com.facebooklogin.example

// this is important, next command will error out if skipped
ionic build

npx cap add ios

npx cap add android

Now we have a hybrid app that with the help of Xcode or Android Studio, we can run on our phones. Now off to Facebook to create our Facebook application that allows us to use the Facebook Login product. When you are done creating your Facebook app, we will move to the next step. I followed the steps provided by Ionic here.

Facebook Plugin

Back at your terminal, we will install the native facebook plugin.

ionic cordova plugin add cordova-plugin-facebook4 --save --variable APP_ID="**************" --variable APP_NAME="Facebook Login"

npm install @ionic-native/facebook

npx cap sync

The last command (npx cap sync), syncs new native packages into the Capacitor build for all added platforms. It will also prompt you to add various items to your Info.plist file (for iOS). I ran into some issues just copying and pasting them directly, so below is what they should look like to save you some time.

<key>FacebookAppID</key>
<string>$APP_ID</string> // replace $APP_ID will real APP ID

<key>FacebookDisplayName</key>
<string>$APP_NAME</string>// replace $APP_NAME will real APP Name

// you don't need this one
<key>FacebookHybridAppEvents</key>
<string>$FACEBOOK_HYBRID_APP_EVENTS</string>

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>

<dict>
    <key>CFBundleURLSchemes</key>
    <array>
        <string>fb$APP_ID</string> // replace $APP_ID will real APP ID
    </array>
</dict>
in the existing CFBundleURLTypes entry of your Info.plist to work

<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>akamaihd.net</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
        </dict>
        <key>facebook.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
        </dict>
        <key>fbcdn.net</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
        </dict>
    </dict>
</dict>
in the existing NSAppTransportSecurity entry of your Info.plist to work

Coding Time

Ok, I think we are ready for some code... finally! Open up your app.module.ts file and add it should look like this.


import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { Facebook } from '@ionic-native/facebook/ngx'; // HINT::This is what we added!

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    Facebook, // HINT::This is what we added!
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Now open up your tab1.page.ts and add the facebook login code by importing the library, types and creating a simple login method. At the end it should look like this.

import { Component } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook/ngx';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {

  loading: HTMLIonLoadingElement;
  loggedIn: boolean = false;
  facebookResponse: FacebookLoginResponse;

  constructor(
    private loadingCtrl: LoadingController,
    private facebook: Facebook,
  ) {}

  async facebookLogin() {
    this.loading = await this.loadingCtrl.create();
    this.loading.present();

    try {
      const response: FacebookLoginResponse = await this.facebook.login(['email']);
      this.loggedIn = true;
      this.facebookResponse = response;
      this.loading.dismiss();
    } catch (error) {
      console.log('facebookLogin', error);
      this.loading.dismiss();
    }
  }
}

Although it may look like a lot it is really not. We added some loading states just for fun but the real add here is the facebookLogin method. Once we have the response from facebook, we are logged in!

Run a build ionic build followed by npx cap copy and finally npx cap open ios (or android) and build it on your device.

That's it! You have Facebook login on your app.

Helpful links

Posted on by:

fvaldes33 profile

Franco Valdes

@fvaldes33

Baseball player turned web developer. Tech lead @ union.co. Creator of gymjournalapp.com

Discussion

markdown guide