Adding Facebook Login to your Ionic app (in 15 minutes)
Tags: ionic, facebook, tutorial, hybrid
Published: 2019-12-28 20:19:05

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

{% twitter 1204392399176425473 %}

So here it is...

In this quick tutorial we will cover installing the Ionic CLI, starting up an [Ionic](https://ionicframework.com/) project, enabling [Capacitor](https://capacitor.ionicframework.com), installing the [Facebook plugin](https://www.npmjs.com/package/cordova-plugin-facebook4) 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](https://firebase.google.com/) with your Ionic app as a part 2.

## Ionic CLI & Ionic Starter App

Install the Ionic cli and start up a new application.

```shell
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.

```shell
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](https://developers.facebook.com/) 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](https://ionicframework.com/docs/native/facebook).

## Facebook Plugin

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

```shell
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.

```xml
<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.

```ts

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.

```ts
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
- [Ionic](https://ionicframework.com/)
- [Ionic Native - Facebook](https://ionicframework.com/docs/native/facebook)
- [Facebook Connect Plugin](https://www.npmjs.com/package/cordova-plugin-facebook4)
- [Capacitor](https://capacitor.ionicframework.com/docs/)
- [Facebook Developers](https://developers.facebook.com/)