Firebase Tutorial: Getting Started
Learn Firebase fundamentals including saving data, real-time sync, authentication, user status and offline support. By Lea Marolt Sonnenschein.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Firebase Tutorial: Getting Started
35 mins
- Getting Started
- Setting up a Firebase Account
- Creating a Connection to Firebase
- Structuring Data
- Understanding Firebase References
- Adding New Items to the List
- Retrieving Data
- Synchronizing Data to the Table View
- Removing Items From the Table View
- Checking Off Items
- Sorting the Grocery List
- Authenticating Users
- Registering Users
- Logging Users In
- Observing Authentication State
- Setting the User in the Grocery List
- Logging Users Out
- Monitoring Users’ Online Status
- Updating the Online User Count
- Displaying a List of Online Users
- Enabling Offline
- Where to Go From Here?
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:
- LoginViewController.swift: Currently uses hard-coded credentials, but you’ll fix that soon.
-
GroceryListTableViewController.swift: A subclass of
UITableViewController
that adds items to a list of local data using aUIAlertController
. - 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:
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:
- Create a free Firebase account.
- Download and add GoogleService-Info.plist to your app.
- 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.
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:
This is a container for your project’s Firebase services. You’ll use it to store data and authenticate users. Click iOS.
Enter com.raywenderlich.grocr in the iOS Bundle ID field. Click Register app.
Then click Download GoogleService-Info.plist. Follow the instructions and move it to the Grocr project in Xcode.
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.
The last page explains how to connect Firebase when your app starts. Click Next to finish the setup:
Finally, click Continue to the console to start coding!
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:
- You create a reference to the root of the Firebase database.
- Using a URL, you can create a reference to a child location in your Firebase database.
- From the
rootRef
you can usechild(_:)
to create a child reference by passing the child path. This reference is the same as the one above. - Using
itemsRef
, you can create a child reference to themilk
location. - Every reference has
key
. This property tells you what the key name is in the Firebase database.