How To Build A Firebase App With SwiftUI
This is a tutorial on how to build your first SwiftUI based app with Firebase integration. All code is up to date with the current Xcode 11 GM release. We’ll be making a simple todo list app that stores its data in Firebase and requires a login to view the users' todo’s.
First, go to your Firebase console and add a new project. Go through the usual steps and download the plist file generated during setup.
While you’re on Firebase, setup the authentication for email and password and set up a Realtime Database with the following rules. These allow the user to only access their own content.
{
"rules": {
"$uid": {
".write": "$uid === auth.uid",
".read": "$uid === auth.uid"
}
}
}
Once you’ve got that complete, create a new project in Xcode 11 and select Single View App. Call it whatever you’d like, I named mine TODO. Importantly, make sure you select SwiftUI as the user interface, and click Next to save the project.
Before you forget, add that plist file from Firebase now.
Navigate to AppDelegate and configure Firebase in the didFinishLaunchingWithOptions function.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { //Firebase
FirebaseApp.configure() return true
}
Create a new pod file and make sure to include Firebase/Auth as well as Firebase/Database for our purposes. (If this is your first time using pods check out: https://cocoapods.org)
# Pods for TODOpod 'Firebase'
pod 'Firebase/Auth'
pod 'Firebase/Analytics'
pod 'Firebase/Database'
Once set up, run the pod file, exit your TODO project and open up the newly created workspace file. First add a model to define your User.
Now add a model to define your todo data.
Let’s now create the session file. Included are all of the functions you’ll need for Firebase.
Next let’s do the basic view. The home page should display a simple list with clickable items. It should also have a way to log in and out as well as sign up. Finally, it should have a way of adding more todo items. Open up ContentView.swift and setup the view.
Create new SwiftUI view files for logging in, signing up, viewing the todo on the list, details, and adding a new todo. Use functions from the session file to communicate with Firebase. (Check the bottom for a Github link to the completed version if you’re stuck.)
Finally, test and ensure the app all functions correctly, albeit a bit ugly.
I hope this guide helped you create your first SwiftUI app using Firebase. It’s quite a simple app with minimal aesthetic considerations. Feel free to build on this into whatever you’d like. Below is a link to a completed version of the TODO app if you need more guidance. If you need help with SwiftUI, check out the SwiftUI tutorials on Apple’s developer website.