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:
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.
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:
In summary, Firebase allows developers to focus on app development and simplifies the backend development required for these apps.
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.
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.
Once your project has been created, click on it and it will open the project overview that looks something like this:
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:
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.
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.
Next, its time to download your config file.
Download the GoogleService-Info.plist file and insert it into your Xcode project. Hit next.
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.
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.
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.
Lastly, run your app to test your installation. Firebase will check that it initialized correctly.
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.
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.
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:
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:
Click the add collection and name it items. We’re going to add our simple list items to this database.
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.
Your database should now look like this:
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:
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.
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.
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.
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:
Now I’ll drag the buttons touched up inside IBOutlet into our swift file like so:
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!
You can also check your Firestore console in Firebase. You’ll see the new items there as well!
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!
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.
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.
I’ll enable email/password and Google for this example project.
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.
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:
Now run your application and you should see this:
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:
Congrats you have set up Firebase authentication correctly :).
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.