Facebook Authentication With Firebase Using Swift

How to add FB Auth and Segues to a new Swift app

Madhuri Palanivelu
11 min readJan 15, 2020
Photo by Maxwell Nelson on Unsplash

Hi! This article is going to be about a project that I worked on recently; an iOS app that would perform Facebook authentication with Firebase using Swift.

This tutorial assumes that you have dabbled with Swift iOS app development before and that you have a basic understanding of some XCode terminology. It also assumes that you know what Firebase is and what it is used for. If not, feel free to go through the tutorial and learn with external resources side-by-side. Check out the Resources section at the end of the article, to find some helpful links to YT channels, videos, and articles that can help you out!

So to begin with, let’s talk about what this app can do. This app will be using the Facebook SDK and Firebase Authentication to perform a login function. It will basically allow you to use a login button to sign-in to the app using your Facebook credentials and also sign-out of the app as well. I’ll also be showing you how you can use Segues to switch screens and give more functionality for your app, after logging in.

So let’s get started!

You can find the Github link to this project code here.

1. Create a New App with Facebook:

The first step is to make a new app with Facebook for Developers. You can go to this website to get started: https://developers.facebook.com/.

Give your app any name you’d like, and you’ll next get directed to your app’s dashboard which will look something like this:

Facebook App Dashboard

2. Register the App with Firebase:

Next, you have to register your new Facebook app with Firebase, and you also need to set its sign in method. To begin, you’d need to go to the official Firebase website: https://firebase.google.com/ and Go To Console.

Official Firebase Website

You can add a new project and follow the steps afterward. After your project is created:

  1. Select Authentication from the left side of your new project dashboard.
  2. Click on Sign-in Method.
  3. Under the list of Sign-in providers, select Facebook and enable it.

Next, enter in your App ID and App Secret which you can find by clicking on Settings → Basic on the navigation bar to the left of your Facebook App dashboard.

Enabling Facebook Sign-in Method

You will need to copy the OAuth Redirect URI and save it for later. Go to your Facebook app dashboard and add a product by clicking on PRODUCTS at the bottom of the navigation bar. Next, click on Set Up on the Facebook Login product option. Select on iOS to start the configuration process.

Let’s go through each of the steps mentioned in the Quickstart guide:

2.1 Set Up Your Development Environment:

First, you’ll need to know what Cocoapods is and why you need it for this project. Cocoapods helps manage library dependencies that you may need for your project. It maintains these libraries in something called a Podfile that gets created with your Xcode project. According to the official website:

“Ultimately the goal is to improve discoverability of, and engagement in, third party open-source libraries by creating a more centralized ecosystem.”

If you don’t have Cocoapods installed on your system, take a look at this video to learn how to set it up.

You’re going to need to add the FacebookSDK dependencies. After opening up a new Xcode project, you will need to set up a Podfile. To do this, cd to your Xcode project directory and complete the following steps:

pod init

This first step above will create your podfile in your project directory. Open up the podfile using any text editor, and add the following pods into the file:

pod ‘FacebookCore’
pod ‘FacebookLogin’
pod ‘FBSDKCoreKit’
pod ‘FBSDKLoginKit’
pod ‘Firebase/Core’
pod ‘Firebase/Auth’

Note: I believe that perhaps not all four of these Facebook pods are required for this application, but for the time being I used all these pods just in case when I made my app. Do let me know in the comments below, if you tried it out and if we can remove some of them!

After saving the podfile, go back to the terminal:

pod install

This will also create a .xcworkspace file. This is the file you should always use to create your app with Xcode.

The Podfile

2.2 Add Your Bundle Identifier:

Copy and paste your Bundle Identifier into this field, from your new Xcode workspace file. You can find it here:

XCode IDE General Pane -> Project Target

2.3 Enable Single Sign On for Your App:

Enable Single Sign On by setting the toggle to Yes.

2.4 Configure Your info.plist:

You can set the app’s metadata by modifying the info.plist file on the project navigation window on XCode. Right-click on it and Open With → Source Code. Add this towards the end of the file (I’ve added the last closing tags so that you know where to paste the code.):

2.5 Connect App Delegate:

The code given in the guide is in Objective-C so I’ve re-written it into Swift here. It's a bit more updated too. The AppDelegate file is responsible for performing functions pertaining to the different states your app can go through. For example, if you’re using an app and your phone rings, a function called applicationWillResignActive would be called.

These need to be imported to the AppDelegate.swift file:

Next, add the following functions to the AppDelegate class:

The first function, didFinishLaunchingWithOptions, is called right before the app loads. So, you’re going to be configuring Firebase and the Facebook SDK with the app when this function is called. One of the functions of the ApplicationDelegate is required to help the app switch to the native Facebook app on your phone.

What happens under the hood, is that after the user signs into your app, it switches over to the native Facebook app on the user’s phone (assuming they have it), asks for user permission and credentials, and passes them back to your app to login.

When your app is switched back to, from the native Facebook app, the application method needs to be called. It handles the final proper login through Facebook.

2.6 Add the Facebook Login Button:

In the ViewController.swift file, complete the viewDidLoad() method with this code:

This code generates a Facebook Login Button.

2.7 Check Current Login Status:

As mentioned in the guide, your app can only have one person logged in at a time. Each person who logs in can be represented using the AccessToken. The use of this is to make sure the switch to the native Facebook app doesn’t happen if someone has already been given access to the app. So you can use this code:

Note: Personally, I have not used this in my code. You can log out of your device from your Facebook settings if you want to try out entering your credentials each time.

2.8 Ask For Permissions:

You can add additional read permissions so that the user can get prompted to grant your app with the requested permissions. In this app, you can use their public profile and their email. You need to add the line to the viewDidLoad() method.

loginButton.permissions = ["public_profile","email"]

3. Add your OAuth Redirect URI:

Remember the OAuth Redirect URI you saved from Step 2? You’ll need to add it to your Facebook app by going to PRODUCTS → Facebook Login → Settings → Valid OAuth Redirect URIs.

4. Adding Firebase:

The next important step is to add Firebase to your iOS app. To do this, go to your Firebase app dashboard, and click on this to add the app:

In the Firebase Setup Wizard that appears, follow the first step to register your app by mentioning the name of your app and its Bundle identifier (2.2) . For the upcoming steps follow this brilliant tutorial from 4:00 to 5:44 to learn about the GoogleService-info.plist file and how to set it up. The next steps talk about adding the FirebaseSDK which you have already done while installing the pods in the beginning.

5. Final ViewController Code and Authentication with Firebase:

Finally, you’ll need to add some new functions to the viewController. They are loginButton:didCompleteWithResult:error: and loginButtonDidLogOut:. These functions are part of LoginButtonDelegate which is, in turn, a delegate object of FBLoginButton.

A delegate is an object that responds to certain activities performed by the app.

According to Apple,

Every app must have an app delegate object to respond to app-related messages. For example, the app notifies its delegate when the app finishes launching and when its foreground or background execution status changes.

For example here, loginButton:didCompleteWithResult:error: is sent to the delegate when the login button is used and loginButtonDidLogOut: is sent to the delegate when the logout button is used.

So this will be the final updated code for the View Controller:

The Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in is important because this line retrieves the Facebook access token from the user and converts it into the Firebase credentials.

When you run your app now, you can log in with your Facebook credentials and you can also log out. (I’ve included a background image in my app).

Now, I promised to show you how you can add some sort of functionality to this app, other than just Facebook Authentication with Firebase. I created a small example of adding a segue that opens after logging onto the app. You can generate a random famous quote or go to the Log Out screen. It probably isn’t a very useful application, but it can give you an idea of how to start building the app further to your liking, by adding another viewController for your app after authentication.

6. Adding Another Screen to the App:

This article was a great help in learning how to add another viewController and bind them both with a segue. Definitely follow it, to understand how to proceed.

The first viewController will have code that performs the segue from the first viewController to the second. In the article mentioned above, they create a SecondViewController.swift file. That file, in this example, will be containing the code that selects a random quote out of a small list. It will also contain the code that dismisses the second viewController and returns back to the first viewController. All of these functions can be added as Actions to a Button. I’ll discuss what this means in a bit.

6.1 Performing the Segue:

Before closing the loginButton:didCompleteWithResult:error: function, you need to add the following line:

performSegue(withIdentifier: "mainScreen", sender: nil)

This line is responsible for changing the current screen to the new screen where the user can generate quotes. As per the article mentioned, I’ve given the second viewController an identifier name called “mainScreen”.

6.2 Quote Generation:

This is a simple hard-coded list of quotes that gets randomly generated to the user. The result label will be used to display the resulting random quote. If you remember, the viewDidLoad function is responsible for performing operations while the app is loading. There isn’t any requirement as such from this viewController in this example, so it can be left empty.

6.3 Dismissing the Current Screen:

A button can be used here to return back to the Log Out screen. By clicking on this button the Quote Display screen will be closed and the previous Log Out screen will come back into the frame. The code to do this can be included in the second viewController file too:

In order to associate these functions with the buttons (Action as a Button as mentioned earlier) that have been added to the second storyboard (as per the article mentioned above), you need to do the following:

  1. Go to Editor → Assistant. You’ll now have your second storyboard and your second viewController file side by side.
  2. Click on the button(or any widget) you’d like to make a function for.
  3. Then while pressing the Control key, click and drag from the widget onto the viewController file and release. You will then get a little window that will let you name your widget and it will connect the widget to your code.
Eg: onCloseButton connects the action to the Go Back to LogOut button

Now once you Log In using your Facebook credentials, you’ll see this:

And there you have it! That’s how you add a new screen to your authentication app!

7. Troubleshooting:

If you get an error relating to the simulator like “Falling back to loading access token from NSUserDefaults because of simulator bug”, then you’ll need to use a real iOS device rather than the simulator.

In case you get an error like “Could not build Objective-C module ‘Firebase’ ” near your Firebase import, then follow these steps:

  1. Quit Xcode.
  2. Delete project’s temp files located at ~/Library/Developer/Xcode/DerivedData
  3. Delete ProjectName.xcworkspace
  4. Delete Podfile.lock file and Pods folder
  5. Run pod install.
  6. Open the newly created ProjectName.xcworkspace file and build.

8. Resources:

Well, this (finally) marks the end of this tutorial! I hope you guys learned something different, and that this article was able to introduce you to not only an interesting project but also to some great teachers and creators out there. The resources that I’ve linked to throughout the article really helped me with this project when I was working on it.

It wouldn’t be fair if I didn’t give a shoutout to all the creators and authors that I got some help from, so here are all of their links! (Including the ones used in this article):

  1. Learn iOS App Development - https://www.youtube.com/codewithchris
  2. How to Install Cocoapods in One Minute by Chris Ching-https://www.youtube.com/watch?v=MS2Ue7y_I4w
  3. Firebase Tutorial (2018)for iOS by Chris Ching-https://www.youtube.com/watch?v=JV9Oqyle3iE
  4. (iOS) Facebook Login Button by Kenta Kodashima-https://medium.com/@KentaKodashima/ios-facebook-login-button-fc715818b410
  5. Using Firebase to Integrate Facebook Login in iOS Apps by Simon Ng-https://www.appcoda.com/firebase-facebook-login/
  6. Move between ViewControllers with Segues — iOS # 9 by Andy O'Sullivan-https://appsandbiscuits.com/move-between-view-controllers-with-segues-ios-9-7e231159e8f4
  7. https://stackoverflow.com/questions/41709912/error-could-not-build-objective-c-module-firebase

Thank you so much for reading. Happy Coding!

--

--

Madhuri Palanivelu

Software Engineer | UX, Tech, and Self-Care Enthusiast