How to use Firebase with your iOS App – Ultimate Guide

Firebase is a powerful tool for app developers. It allows developers to focus in on app development without having to manage a lot of infrastructure.

It simplifies the backend requirements of an app so you can focus on building a great user experience. I’ve worked with Firebase many times and love using it for my mobile apps.

How to use Firebase with your iOS app:

  • Create a new Firebase Project
  • Add your iOS app to your new Firebase project
  • Add firebase config file into your Xcode project
  • Setup CocoaPods
  • Install Firebase Pods
  • Configure Firebase in app code
  • Connect Firebase database
  • Setup Firebase authentication

Firebase has made my life as an iOS developer a lot easier and helps me sleep at night. Read on to learn how simple it is to get setup and running using Firebase.

What is Firebase? And why should I use it?

Firebase’s motto is to help mobile teams succeed. They do this by managing infrastructure such as databases, authentication APIs and push notifications for you. There are no servers for you to manage or databases for you to spin up. It stores and syncs app data in their cloud and scales effortlessly.

Here’s a list of features that Firebase offers:

  • Store and sync app data globally in real time
  • Cloud functions – run code without servers
  • Simple authentication
  • Web asset hosting
  • Cloud storage
  • Realtime crash reporting
  • Performance monitoring
  • Messaging and notifications
  • Backed by Google and battle tested
  • And more …

In summary, Firebase allows developers to focus on app development and simplifies the backend development required for these apps.

Create a new Firebase Project

The first step to using Firebase head over to https://firebase.google.com/ and create an account.

Once you’ve created an account head over go to your Firebase Console and select Add Project.

firebase

A dialog will pop up allowing you specify the name of your project. I checked both boxes and used default options. Click Create project when you’re done filling out this dialog. Firebase will then spin up your project.

Adding an iOS App to your Firebase Project

Once your project has been created, click on it and it will open the project overview that looks something like this:

firebase_1

The next step is to add an iOS app. click the iOS icon on this screen to get started. This should result in opening a form like this:

firebase_2

Your iOS bundle ID is the same one you created when you made an Xcode project. You can find your Bundle Identifier in the General tab for your app’s primary target in Xcode.

firebase_3

Make sure you copy the same bundle identifier into the Firebase form. It is recommended that your bundle identifier start with com.

The other fields App nickname and App Store ID are optional. Fill the nickname in if you’d like and fill in App Store ID if you have one. Hit Register App to continue.

Add firebase config file into your Xcode project

Next, its time to download your config file.

firebase_4

Download the GoogleService-Info.plist file and insert it into your Xcode project. Hit next.

Install Firebase SDK using CocoaPods

The next step is to install Firebase SDK to your Xcode project using CocoaPods. If you don’t have CocoaPods installed, read this article I wrote on it.

Once you have CocoaPods installed, add pod ‘Firebase/Core’ to your Podfile. Save your podfile and run pod install.

firebase_5

My Podfile looks like this:

# platform :ios, '9.0'

target 'list' do
  use_frameworks!

  pod 'Firebase/Core'
  pod 'Firebase/Firestore'

end

Remember to open up the XCWorkspace on Xcode from now on, not the Xcodeproj. The workspace includes your pods as well as your own code.

Configure Firebase in app code

Next, you’ll need to add initialization code to your project. This will setup Firebase when your app starts. Copy and paste the code from the Firebase website.

firebase_6

Lastly, run your app to test your installation. Firebase will check that it initialized correctly.

firebase_7

If all the checks passed, congrats, you’ve setup Firebase for your iOS app. In the rest of this article, we’ll go over some of the common uses cases of Firebase.

Connect Firebase Database

We’ll be building a simple list app as an example for this article. It will connect to a Firebase database and sync with it in real time. Changes from the web will be reflected in the app and vice versa. Let’s get started.

Open up your app in Firebase and click the Database option on the left hand panel.

firebase_8

Next you’ll be presented with an option to use Cloud Firestore or Realtime database. For this article, we’re going to use Cloud Firestore. You can read the information on the page to decide what database solution is right for you.

Once you’ve selected Cloud Firestore, you’ll be presented with this dialog:

firebase_9

We’re going to select to Start in test mode. This will allow us to quickly develop without worrying about setting up permissions. Click Enable, Firebase will then set up your Cloud Firestore. Once its been setup you should see a screen like this:

firebase_10

Click the add collection and name it items. We’re going to add our simple list items to this database.

firebase_11

We’re going to add our first item in our collection. This is going to be a simple item with only a name field that is a string.

firebase_12

Your database should now look like this:

firebase_13

Now let’s work on retrieving this data and displaying it in our application.

Add pod ‘Firebase/Firestore’ to your Podfile and run pod install.

Open up Xcode and open up the view controller that launches when your application starts. I never use storyboards in my apps and you can read more on how to make an iOS app without storyboards.

In your view controller add the following code to your viewDidLoad:

import UIKit
import Firebase

class MainViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let db = Firestore.firestore()
        db.collection("items").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    print("\(document.documentID) => \(document.data())")
                }
            }
        }
    }
}

Remember to import Firebase at the top of your file. Once you run your app, you should be able to read in console:

1 => ["name": Buy toothpaste]

Congrats! You’ve successfully read from your database. Now let’s display this data in a nice list in our app’s user interface.

We’re aiming to build this:

firebase_14

First go into your XIB file and create a tableview. Expand it so it fills the view and set constraints for leading, trailing, top and bottom.

firebase_15

Next, we’ll need to subclass UITableViewDelegate & UITableViewDataSource in our view controller and add an IBOutlet to the table view. We’ll also create an array to store all the items retrieved from the database. The top of your view controller file should look something like this:

import UIKit
import Firebase

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!
    var items = [String]()

Now we’ll need to add three lines to our viewDidLoad function for setting up our table view:

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self

We’ll need to complete our table view data source and delegate functions.

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
    cell.textLabel?.text = items[indexPath.row]
    return cell
}

Our complete code should look something like this:

import UIKit
import Firebase

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!
    var items = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.delegate = self
        tableView.dataSource = self

        let db = Firestore.firestore()
        db.collection("items").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    if let name = document.data()["name"] as? String {
                        self.items.append(name)
                    }
                }
                self.tableView.reloadData()
            }
        }
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }
}

If you add another document to our firestore, you should it reflected in your app.

firebase_16

Now you’ve learned how to read from a Firestore database and display it in your user interface.

Next, we’re going to learn how to write to this database and add items to our list. To do this we’re going to implement a simple button that adds a new item to this list.

firebase_17

In the interface builder, I deleted the bottom constraint of the table view. Then I shrunk the table views height and added a button to the bottom of the screen. I set the buttons constraints as follows:

firebase_18

Now I’ll drag the buttons touched up inside IBOutlet into our swift file like so:

firebase_19

Inside that IBOutlet function I’ll add the following code:

@IBAction func addItemClicked(_ sender: Any) {
    var ref: DocumentReference? = nil
    ref = db.collection("items").addDocument(data: [
        "name": "new item!",
    ]) { err in
        if let err = err {
            print("Error adding document: \(err)")
        } else {
            print("Document added with ID: \(ref!.documentID)")
        }
    }
    reloadTable()
}

I’ll add a new line to clear out the items array and also refactor my read code, so the top of my file now looks like this:

    let db = Firestore.firestore()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.delegate = self
        tableView.dataSource = self
        reloadTable()
    }

    func reloadTable() {
        items = [String]()
        db.collection("items").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    if let name = document.data()["name"] as? String {
                        self.items.append(name)
                    }
                }
                self.tableView.reloadData()
            }
        }
    }

Now run your application click the button at the bottom of the screen. It should add a new item to your table. Click more and you’ll add new items!

firebase_20

You can also check your Firestore console in Firebase. You’ll see the new items there as well!

firebase_21

Since we didn’t give the new documents an ID, a randomly generated one is assigned to them.

Congrats, now you know how to read and write to a Firebase database!

Setup Firebase Authentication

The next topic we’ll tackle is adding Firebase authentication to your iOS app. This is a common problem developers face. Allowing users to sign up to your app through email or social logins is a common feature requirement.

Having authentication features allows your app to save settings and data specific to each user. This usually results in more personalized and better user experience. Firebase makes this authentication simple, as it integrates with popular social platforms such as Facebook, Twitter, Google and more.

For this section, we’re going to create a new project. I’m going to call this project “authentication”. You’ll need to add the following pods to your Podfile.

pod 'FirebaseUI'
pod 'Firebase/Core'

Go ahead and run pod install. FirebaseUI makes adding logins to your project really simple. Remember to open up the workspace and not the xcodeproj file after you install your pods.

Now we need to enable the firebase authentication methods in our firebase console. Go to your firebase console and click the authentication option in the left hand panel.

firebase_22

Click the set up sign-in method button in the middle of the screen. You’ll be presented with a page to enable the sign-in methods you’d like.

firebase_23

I’ll enable email/password and Google for this example project.

firebase_24

You will need to add a reversed client ID as a URL scheme in your Xcode project. You can find this value in the GoogleService-Info.plist file.

firebase_25

Now that authentication has been configured to work with our app, its time to jump into the Swift code. Import Firebase and FirebaseUI into your app delegate. Next we’ll add the following code to our didFinishLaunchingWithOptions method in our AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    let authUI = FUIAuth.defaultAuthUI()
    let providers: [FUIAuthProvider] = [
        FUIGoogleAuth()]
    authUI?.providers = providers
    authUI?.delegate = self

The above code configures our firebase app, creates our FirebaseUI view controller and sets the providers we’re going to be using. In our case we’re just using Google. Email does not need to be specified here since it will be stored in our Firebase app and is not related to another vendor. We also set the delegate to be self.

Next, we’re going to display our authentication controller onto the screen. We’ll use the following code to do so:

guard let authViewController = authUI?.authViewController() else { return true }

window = UIWindow(frame: UIScreen.main.bounds)
window!.rootViewController = authViewController
window!.makeKeyAndVisible()
return true

Make sure to clear out the Main interface line in your project general settings:

firebase_26

Now run your application and you should see this:

firebase_27

If you go through the sign in flows, you should be able to create accounts for yourself. You can check this in your Firebase console:

firebase_28

Congrats you have set up Firebase authentication correctly :).

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts