Firebase Tutorial: Getting Started

Learn Firebase fundamentals including saving data, real-time sync, authentication, user status and offline support. By Lea Marolt Sonnenschein.

4.4 (16) · 1 Review

Download materials
Save for later
Share
Update note: Lea Marolt Sonnenschein updated this tutorial for iOS 14, Swift 5 and Xcode 12.5. David East wrote the original.

Firebase is a mobile backend-as-a-service that provides powerful features for building mobile apps. Firebase has three core services:

  • Realtime database
  • User authentication
  • Hosting

With the Firebase iOS SDK, you can use these services to create apps without writing any server code!

In this tutorial, you’ll learn the fundamentals of Firebase by making a collaborative grocery list called Grocr. When a user adds items to the list, they instantly appear on everyone’s devices.

But you’re not going to stop there! You’ll tweak Grocr to work offline, so the list stays in sync even with a spotty grocery store data connection.

As you work, you’ll learn how to:

  • Save data to a Firebase database.
  • Sync data in real time.
  • Authenticate users.
  • Monitor online users.
  • Enable offline support.

Getting Started

Download the starter project by clicking Download Materials at the top or bottom of the tutorial.

Grocr contains three view controllers:

  1. LoginViewController.swift: Currently uses hard-coded credentials, but you’ll fix that soon.
  2. GroceryListTableViewController.swift: A subclass of UITableViewController that adds items to a list of local data using a UIAlertController.
  3. OnlineUsersTableViewController.swift: This controller uses Firebase’s presence feature to display all of the users currently online.

In addition to the view controllers, Grocr has two models: GroceryItem.swift and User.swift.

Build and run. You’ll see the app looks like this:

Grocr app screens

There’s a hard-coded user in the app for now. Go ahead, tap Login and play with the app. The app currently works with local data only.

Next, you’ll use Firebase to bring the app to life.

Setting up a Firebase Account

There are three main steps to setting up Firebase in an iOS project:

  1. Create a free Firebase account.
  2. Download and add GoogleService-Info.plist to your app.
  3. Tell Firebase to start when your app launches.

To create a Firebase account, visit the Firebase homepage. Click Get started in the bottom left of the page, and enter the credentials for your Google account, if you aren’t signed in already. If you don’t have a Google account, you’ll need to create one first, which you can do here.

Now you have a clean Firebase console. Don’t worry about forking over any money: you can do everything in this Firebase tutorial with the free plan.

It’s time to create your first project. Click Create a project.

Firebase console

In the dialog that appears, enter Grocr as the Project name and click Continue.

Turn off Enable Google Analytics for this project. Click Create project and wait for it to load. Then, click Continue to get to the project’s dashboard:

Project setup

This is a container for your project’s Firebase services. You’ll use it to store data and authenticate users. Click iOS.

Firebase dashboard

Enter com.raywenderlich.grocr in the iOS Bundle ID field. Click Register app.

Add iOS app

Then click Download GoogleService-Info.plist. Follow the instructions and move it to the Grocr project in Xcode.

Download Google plist

When prompted by Xcode, check Copy Items if needed.

Return to your Firebase project’s webpage. This page describes how to install the Firebase SDK.

Instead of CocoaPods, this project uses Swift Package Manager to manage the SDK. It’s included in the starter project, so click Next.

Install Firebase SDK

The last page explains how to connect Firebase when your app starts. Click Next to finish the setup:

Add Firebase to your app

Finally, click Continue to the console to start coding!

Setup finished

In Xcode, open AppDelegate.swift. Add this code before the return statement within application(_:didFinishLaunchingWithOptions:):

FirebaseApp.configure()

Now you’ll create a connection to Firebase.

Creating a Connection to Firebase

With your Firebase app set up, open GroceryListTableViewController.swift. Add these new properties:

let ref = Database.database().reference(withPath: "grocery-items")
var refObservers: [DatabaseHandle] = []

Using reference(withPath:), you establish a connection to your Firebase database at a given path. In the documentation, Firebase refers to these properties as references because they refer to a location in your Firebase database.

Once you have a reference, you’ll start adding observers to it so that you get notified when a change occurs. It’s best practice to keep track of the references you add, so you can clean them up later. You added refObservers for this purpose. You’ll see this in action a little bit later in this tutorial.

In short, these properties let you save and sync data to the given location.

You’ll notice it doesn’t use the base URL. Instead, it uses a child path grocery-items. The Firebase database is a JSON NoSQL database, so all data stores as JSON.

JSON is a hierarchical tree of key-value data structure. Keys are objects that can contain values that point to other objects.

With Firebase, the key is a URL and the value is arbitrary data that could be a number, string, Boolean or object.

Structuring Data

No matter how it’s formatted on the client, all data stored in Firebase is JSON. Look at the following sample JSON data:

// The root of the tree
{
  // grocery-items
  "grocery-items": {

    // grocery-items/milk
    "milk": {

      // grocery-items/milk/name
      "name": "Milk",

      // grocery-items/milk/addedByUser
      "addedByUser": "David"
    },

    "pizza": {
      "name": "Pizza",
      "addedByUser": "Alice"
    },
  }
}

In the JSON tree above, there’s a path mapped to every piece of data. You can traverse down the tree and retrieve data at deeper locations.

Here, you can retrieve all grocery items by using the path:

grocery-items

To only get the first grocery item, you can navigate to the child path:

grocery-items/milk

Since all Firebase keys map to paths, the key names you choose are especially important.

Understanding Firebase References

A Firebase reference points to a Firebase location where the data is stored. Multiple references share the same connection.

Look at this sample code:

// 1
let rootRef = Database.database().reference()

// 2
let childRef = Database.database().reference(withPath: "grocery-items")

// 3
let itemsRef = rootRef.child("grocery-items")

// 4
let milkRef = itemsRef.child("milk")

// 5
print(rootRef.key)   // prints: nil
print(childRef.key)  // prints: "grocery-items"
print(itemsRef.key)  // prints: "grocery-items"
print(milkRef.key)   // prints: "milk"

Here’s what’s going on:

  1. You create a reference to the root of the Firebase database.
  2. Using a URL, you can create a reference to a child location in your Firebase database.
  3. From the rootRef you can use child(_:) to create a child reference by passing the child path. This reference is the same as the one above.
  4. Using itemsRef, you can create a child reference to the milk location.
  5. Every reference has key. This property tells you what the key name is in the Firebase database.