How to Code for Firebase Authentication in Swift – The Quick and Easy Guide

How to Code for Firebase Authentication in Swift

Every app needs to know the identity of its users. That is how an app can collect data, personalize services and provide value. That is why a good authentication service is imperative to the development of an app.

Firebase Authentication gives you the complete package that enables you to sign up or sign in your users, monetize your app and collect data.

Firebase gives you the tools to develop high-quality apps, grow your user base, and earn more money. Firebase supports Android, iOS, Web, C++ and Unity platforms. They cover the essentials so you can monetize your business and focus on your users.

Firebase has a bevy of tools for development, authentication, testing and growing your product to the audience.

Let’s talk about Firebase Authentication

Firebase Authentication provides easy-to-use SDKs, backend services, and ready-made UI libraries for a complete authentication solution for your app. It supports authentication using passwords, phone numbers, email, Google, Facebook and Twitter, and more.

Implementation Steps

  1. Enable sign-in methods: Enable sign-in methods which are available in firebase console.
  2. Design User Interface flows for your sign-in methods: Based on the sign-in method being used, you will need to customize the application flow and user interface. For password based login, the app will need to display fields like email and password and if you are going with phone number based authentication then user interface should be customized for phone number entry and verification of the code which is sent to user’s phone.
  3. Integrate Firebase SDK and code for Authentication: Pass the desired information to the Firebase Authentication SDK to create user id or to login.

Basic Requirements to start with Firebase

Before you start, you need a few things set up in your environment:

  • Xcode 8.0 or later
  • An Xcode project targeting iOS 8 or above
  • Swift projects must use Swift 3.0 or later
  • CocoaPods 1.2.0 or later

Add Firebase to your project

To add Firebase to your app, you will need a Firebase project and a Firebase configuration file for your application.

  1. Create a project in firebase console by logging in to your Google account.
  2. Select platform (iOS, Android or Web) after creation of the project. By clicking on iOS you will be prompted to add application information like iOS bundle ID and other information, including optional fields.
  3. After setting up the platform, you will see an option to download a GoogleService-Info.plist file. Go ahead and add this file to your project.

Install SDK for Firebase and Authentication

The easiest way to install the SDK is by using Cocoapods dependency manager.

 1. Go to your project directory from terminal.

$ cd your-project directory

2. Create a Podfile (If you already have a pod file, you can skip this step)

$ pod init

3. Open the Podfile and add the pods in the file that you wish to install. Like this:

pod 'Firebase/Core'
pod 'Firebase/Auth'

4. Install the pods from terminal and open the .xcworkspace file to see the project in Xcode.

$ pod install
$ open your-project.xcworkspace

Configure Firebase App in Swift

After opening workspace you have to initialize and configure with Firebase App.

  1. Import Firebase module in your Application Delegate file:
  2. import Firebase
  3. Configure Firebase App in your application’s application:didFinishLaunchingWithOptions: method (It will be communicated with the GoogleService-Info.plist file):
FirebaseApp.configure()

Create New User / Sign Up Process

There is a function in Firebase Authentication to create the user in the firebase system.

Auth.auth().createUser(withEmail: "user@email.com", password: "PASSWORD******") { (user, error) in
    if let error = error {
        print(error.localizedDescription)
    }
    else if let user = user {
        print("Sign Up Successfully. \(user.uid)")
    }
}

This is where you will need to enter email and password as parameters and you will get error or user object in response. After completing the signup process, the user would already be logged in to the system.

Sign In / Login Process

There is a function in Firebase Authentication to sign in from the app to the firebase system.

Auth.auth().signIn(withEmail: "user@email.com", password: "PASSWORD******") { (user, error) in
    if let error = error {
        print(error.localizedDescription)
    }
    else if let user = user {
        print(user.uid)
    }
}

Get User Information

After completing the sign up or sign in process, we can get the user information. We can access the current user object using the following code:

let currentUser = Auth.auth().currentUser
print(currentUser.uid)

You can get more information like email, displayName, and photoURL from the user object itself. To get that, we need to update the user information using the code

if let user = user {
  let uid = user.uid
  let email = user.email
  let photoURL = user.photoURL
}

Update User Information

We can update user information by creating a profile change request.

let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = "Carter Keneth"
changeRequest?.commitChanges(completion: { (error) in
    if let error = error {
        print(error.localizedDescription)
        self.view.makeToast(error.localizedDescription)
    }
})


If you wish to update the 
photoURL then you have to give a URL of an image which is hosted to any web server or you can also use Firebase Storage to upload the user’s profile picture.

Logout / Sign Out User

Firebase provides API to logout from the application session.

if Auth.auth().currentUser != nil {
    do {
        try Auth.auth().signOut()
    }
    catch {
    }
}

Find The List of Users

You can access the list of users from the firebase console.

From the console, you can perform operations like reset password, disable account and delete account.

Conclusion

Firebase happens to be the best tool for authentication. This article will help you gain a basic understanding of getting started with Firebase and authentication. Using this as a starting point, you can implement sign in, sign up, update user information and logout functionalities using Firebase.

Thanks for reading, Hope you liked the article.

Happy Coding!

Checklist To Secure Your Mobile App From Every Possible Threat

Download Checklist
*We will send the checklist to your inbox and keep you updated with the latest trends and insights on app development to keep you on top of your game.

Leave a Reply