iOS Facebook Login Using FirebaseUI in 19 MINS

Firebase iOS

If you look at any iOS app these days, you’re most likely going to see the Facebook login button on the login screen.

You can integrate Facebook Login to your iOS app easily using FirebaseUI.

Let’s get started!

Add Firebase to Your iOS Project

I have previously written an article about this and you can easily follow the steps to know how to Add Firebase to Your iOS Project.

Once Firebase is connected to your iOS project, the next step would be to install Facebook pod.

Install FirebaseUI/Facebook pod

Go to the Project Navigator at the top left in your Xcode project → PodsPodFile, click to open it.

Then, Add Facebook Pod under pod 'Firebase/Core' code and save it.

pod 'FirebaseUI/Facebook'

Finally,  install the newly added Facebook Pod by opening up Terminal and navigate to the location of your Xcode project, and run

pod install

Once it’s done, you may want to close your Xcode project and re-open it by double clicking .xcworkspace file.

Add FirebaseUI Configuration Code for Facebook

Import FirebaseUI at the top of ViewController.swift file.

import FirebaseUI

You may see an error like “No such module ‘FirebaseUI.” If you get this error, close the Xcode project and reopen it and wait for a few seconds, then add the import statement again and it should work.

Create viewDidAppear() method in the ViewController.swift file and add the following code.

override func viewDidAppear(_ animated: Bool) {
  let authUI = FUIAuth.defaultAuthUI()
  let providers: [FUIAuthProvider] = [FUIFacebookAuth()]
  authUI!.providers = providers
  let authViewController = authUI!.authViewController()
  self.present(authViewController, animated: true, completion: nil)
}

In the first line, create AuthUI instance by invoking defaultAuthUI method on FUIAuth object.

Then, define providers variable which is a type of FUIAuthProvider. As you can see, it’s an array that contains one item which is FUIFacebookAuth().

This is where you can add different auth providers like Google, Twitter etc depends on your app requirements.

Set the providers array to the property called provider of authUI object.

Since FirebaseUI provides authViewController out of the box, you can get the instance of it by invoking authViewController() method on authUI object.

Finally, show the auth view controller on the screen using present() method by passing authViewController as a first argument.

That’s it! Let’s run ► it and see what happens.

And, we get a thread error.

Go to the debug area in your Xcode, and if you scroll down to the middle, there will be a message like below which is telling me to set FacebookAppID, FacebookDisplayName to the info.plist.

Let’s go and get those from the Facebook for Developers page.

Set Facebook App ID and Facebook Display Name to info.plist

To get that, hop over to the developer.facebook.com page and login.

facebook-my-apps-create-app

At the top right, you can see My AppsCreate App from the drop down which will bring a dialog box.

create-a-new-appid-facebook

Give it a Display Name which is important because this is what your users will see when they are trying login through Facebook from you app.

And, hit Create App ID.

Once Facebook App ID has been created, it will take you to the App Dashboard page choose settings (from the sidebar)  Basics.

facebookappid-appsecret

In there, you can see FacebookAppID and FacebookDisplayName on the right side.

Let’s set those information to the info.plist in your Xcode project.

Switch back to XcodeProject Navigator info.plist → On the right side, click the + icon which will appear next to Information Property List at the top when you mouseover to it.

Create two properties, FacebookAppID and FacebookDisplayName, and set their values (which you can get it from the Facebook Developer console).

If you look at any iOS app these days, you're most likely going to see the Facebook login button on the login screen.  You can integrate Facebook Login to your iOS app easily using FirebaseUI.  If you've not used FirebaseUI in your iOS app before, you're missing a big part.  Let's get started!  Add Firebase to Your iOS Project Install FirebaseUI/Facebook pod Add FirebaseUI Configuration Code for Facebook Login Set FacebookAppID and FacebookDisplayName to info.plist Enable Facebook on Firebase Console Add Firebase to Your iOS Project  I have written an article about it and follow the steps to know how to Add Firebase to Your iOS Project.  Once Firebase is connected to your iOS project, the next step would be to obtain FacebookAppID and Facebook App Secret.  Install FirebaseUI/Facebook pod  Go to the Project Navigator at the top left in your Xcode project → Pods → PodFile, click to open it.  Then, Add Facebook Pod under pod 'Firebase/Core' code and save it.  pod 'FirebaseUI/Facebook'   Finally,  install the newly added Facebook Pod by opening up Terminal and navigate to the location of your Xcode project, and run  pod install  Once it's done, you may want to close your Xcode project and re-open it by double clicking .xcworkspace file.  Add FirebaseUI Configuration Code for Facebook  import FirebaseUI at the top of ViewController.swift file  import FirebaseUI   You may see an error like No such module 'FirebaseUI. If you get this error, close the Xcode project and reopen it and wait for few seconds, then add the import statement again and it should work.  create viewDidAppear() method in the ViewController.swift file and add the following code.  override func viewDidAppear(_ animated: Bool) {   let authUI = FUIAuth.defaultAuthUI()   let providers: [FUIAuthProvider] = [FUIFacebookAuth()]   authUI!.providers = providers   let authViewController = authUI!.authViewController()   self.present(authViewController, animated: true, completion: nil) }  In the first line, create AuthUI instance by invoking defaultAuthUI method on FUIAuth object.  Then, define providers variable which is a type of FUIAuthProvider. As you can see it's an array that contains one item which is FUIFacebookAuth().  This is where you can add different auth providers like Google, Twitter etc depends on your app requirements.  Set the providers array to the property called provider of authUI object.  Since, FirebaseUI provides authViewController out of the box, you can get the instance of it by invoking authViewController() method on authUI object.  Finally, show the auth view controller on the screen using present() method by passing authViewController as a first argument.  That's it!  Let's run ► it and see what happens.  And, got a thread error.  Go to debug area in your Xcode, and if you scroll down to the middle, there will be a message like below which is telling me to set FacebookAppID, FacebookDisplayName to the info.plist.  Let's go and get those from the Facebook for Developers page.  Set Facebook App ID and Facebook Display Name to info.plist  To get that, Hop-over to developer.facebook.com page and login.  At the top right, you can see My Apps → Create App from drop down which will bring a dialog box.  Give it a Display Name which is important because this is what your users will see when they are trying login through Facebook from you app.  And, hit Create App ID.  Once Facebook app has been created, it will take you to the App Dashboard page → choose settings (from the sidebar) → Basics.  In there, you can see FacebookAppID and FacebookDisplayName on the right side.  Let's set those information to the info.plist in your Xcode project.  Switch back to Xcode → Project Navigator → info.plist → On the right side, click the + icon which will appear next to Information Property List at top when you mouseover to it and create two properties FacebookAppID and FacebookDisplayName.     Run  ► the app now, indeed the Sign in With Facebook appeared.     Nice!  Press the Sign in with Facebook button and got the URL Scheme Registration error message in the debug area.  To Add the URL Scheme, select the project root folder at the top left from Project Navigator → Info→ URL Types which is the last one → Add a new item by pressing + button at the bottom.  Set an identifier name to Facebook and URL Schemes to Facebook App ID prefixed with fb.  For Example: fb321832751869519 and make sure to use yours that you can find it from Facebook for developers dashboard  Run the application and press the Sign in with Facebook button. Now, it will take you to the authorization alert view.  It will open Facebook Login Page upon pressing the continue button if you've not logged in with Facebook.  if you've already logged in, it will take you to the Log in With Facebook page and hit Continue and nothing happened.  This is because, you need to enable Facebook on Firebase.  Let's do that next  Enable Facebook on Firebase Console  Go to the Firebase Console Dashboard → Authentication section → Sign-in Methods Tab, → enable Facebook.  Then, click the pencil icon on the right side of the Facebook row which will bring the pop-up window and enable the switch at the top right and hit save.  At this stage, you will need App ID and App Secret in order to complete the enabling process.  Get the App ID and App Secret  from Facebook for Developers App Dashboard.   Copy the OAuth redirect URI which is at the bottom of the window before saving it.  Finally, head back to Facebook for Developers Dashboard → Select the your app → under product on the left bottom → Choose Facebook Login → Settings  Run the application and Log in with Facebook with your credentials.  If everything goes well, you should be able to see a brand new Firebase account created on the Firebase Console under Authentication section.  There you have it :)  Bonus:

Run  ► the app now, indeed the Sign in With Facebook appeared.

Nice!

Add URL Scheme in the Info.plist

Press the Sign in with Facebook button and you will get the URL Scheme Registration error message in the debug area.

fb-urlscheme-registration-error-plist-xcode

To Add that, jump into Project Navigatorselect the Project Root Folder at the top left from  → Info URL Types which is the last one from the bottom → Add a new item by pressing + button at the bottom.

Set an identifier name to Facebook and URL Schemes to your Facebook App ID prefixed with fb.

For Example: fb321832751869519 and make sure to use yours that you find from the Facebook for developers dashboard.

set-urlscheme-identifier-facbook-xcode

Run the application and press the Sign in with Facebook button. Now, it will take you to the authorization alert view. Click continue.

It will take you to the Facebook Login Page if you’ve not logged in with Facebook.

If you’ve already logged in, you’re redirected to Log in With Facebook page and hit Continue and nothing will happen! That will bring us to the next step.

Enable Facebook on Firebase Console

Go to the Firebase Console Dashboard → Authentication section → Sign in Methods Tab, → enable Facebook.

Then, click the pencil icon on the right side of the Facebook row which will bring the pop-up window and enable the switch at the top right and hit save.

enable-facebook-signin-on-firebase-console

At this stage, you will need the App ID and App Secret in order to complete the enabling process. Again, you can find that information on the Facebook Developer console.

Before saving it, copy the OAuth redirect URI which is at the bottom of the window.

Finally, head back to Facebook for Developers Dashboard → My Apps → Choose your app -> under Product which on the left bottom → Choose Facebook Login → Settings.

On the right side, you can see the Valid OAuth Redirect URIs under Client OAuth Settings section.

Paste the URI that you have copied from Firebase to that input field.

Run ► the application and Log in with Facebook with your credentials.

If everything goes well, you should be able to see a brand new Firebase account created on the Firebase Console under the Authentication section.

firebase-authentication-new-user

It works!

As you can see, it will take to the login screen back again which is not user friendly and let’s fix it.

The first step is to check to see if user is logged in or not

Take the authUI object out of the viewDidAppear() and make it as a property of the ViewController.swift. So that, I can use authUI in a multiple places.

let authUI = FUIAuth.defaultAuthUI()

Next,

In the viewDidAppear() method, invoke addStateDidChangeListener() method of auth object that ships with Firebase. This method will be triggered anytime a user is logged in or out.

override func viewDidAppear(_ animated: Bool) {
        
  let providers: [FUIAuthProvider] = [FUIFacebookAuth()]
   self.authUI!.providers = providers
        
     auth.addStateDidChangeListener { (auth, user) in
            if let user = user {
                self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Signout", style: .plain, target: self, action: #selector(self.signOutButtonPressed))
                
                self.showProfileView(user:user)
            } else {
                let authViewController = authUI!.authViewController() self.present(authViewController, animated: true, completion: nil)
            }
            
        }
        
        
   }

Inside addStateDidChangeListener() method, check if the user exists using if let block.

If user exists, create a sign-out button at the top right side of the navigation bar. Then, call showProfileView() method by passing a user as an argument.

If the user variable is set to nil, show the authViewController using present() method.

Pretty straightforward!

Moving on, let’s declare sign-out method.

@objc func signOutButtonPressed() {
        
        do {
            try authUI?.signOut()
        } catch let signOutError as NSError {
            print ("Error signing out: %@", signOutError)
        }
    }

Now, let’s declare showProfileView() and the final output should be like this.

facebook-login-profile

Inside showProfileView() method, add the following code below.

func showProfileView(user:User) {
        
        if let userProfileImg = user.photoURL {
            let img = UIImageView()
            
            if let data = try? Data(contentsOf: userProfileImg) {
                img.image = UIImage(data: data)
            }
            img.frame = CGRect(x:view.frame.size.width / 2 - 50, y:150, width:100, height:100)
            img.layer.cornerRadius = 50
            img.clipsToBounds = true
            view.addSubview(img)
        }
        
        if let userTitle = user.displayName {
            let title = UILabel()
            title.text = userTitle
            title.frame = CGRect(x:0, y:250, width:view.frame.size.width, height:40)
            title.textAlignment = .center
            title.font = UIFont.systemFont(ofSize: 20)
            view.addSubview(title)
        }
        
        let providerTitle = UILabel()
        providerTitle.text = "Logged in via: \(user.providerData[0].providerID)"
        providerTitle.frame = CGRect(x:0, y:275, width:view.frame.size.width, height:40)
        providerTitle.textAlignment = .center
        providerTitle.font = UIFont.systemFont(ofSize: 16)
        providerTitle.textColor = .gray
        view.addSubview(providerTitle)
        
    }

I like building UI programmatically and it’s just my personal preference. If you want to build the UI using storyboard, feel free to do so.

As you can see I have three UI components and nothing fancy,

  • Profile Image
  • Name Title
  • Provider Title

If you want to customize the authViewController, you can do so using extending FUIAuthBaseViewController inside ViewController.swift class.

extension FUIAuthBaseViewController {
    open override func viewWillAppear(_ animated: Bool) {
        self.navigationItem.leftBarButtonItem = nil
        self.navigationItem.title = "Login"
    }
}

In the above code, I have get rid of the Cancel button at the top left side of the authViewController as well as I changed the title from “Welcome” to “Login”.

You can find the full source code on Github.

What are the other features that you would like to know when integrating Facebook Login to your iOS App using FirebaseUI?

Let me know so that I can keep adding it here. 🙂

Comments Count: 0 0