SwiftUI & Firestore — CRUD exercice

In this tutorial, we will learn how to communicate with Firebase Firestore to create, read, update and delete documents using SwiftUI and MVVM.

Sullivan De Carli
Swift Productions
5 min readSep 26, 2022

--

Firebase and SwiftUI logo with 2 iPhones screenshots

Difficulty: Beginner | Easy | Normal | Challenging

Environment : Xcode 14, iOS 16, MVVM, Firebase & SwiftUI

Repository at the end of this article

Introduction

The application will be similar to the Apple Note, it is going to feature to ability to post a note, read it, edit it and also deleting it. We are going to use the Model — View — View Model design pattern, so we have a separation of concern between each action. Let’s get started!

Firebase Set Up

First things is to create a new Xcode project, call it Note.

Then, integrate Firebase to your project, I invite you to check out this article and get back if you don’t know how to set it up:

During the process, make sure to add the two followings dependencies:

  • FirebaseFirestore
  • FirebaseFirestoreSwift

Set Up Firestore

Firestore will be our NoSQL, document based database where we will upload and edit content, head to the Firebase Firestore section in the Firebase console and click on “Create database”:

Then, select “Start in test mode” (will be enough for the purpose of this tutorial) and enable Firestore:

You are now ready to receive and update documents to and from Firestore!

Model

let’s create our Model, this is going to be our reference from where we will post and edit data. It is going to be composed of an identifier and a String which will contain our Note. Go ahead and create a new Swift File and call it Note.

The @DocumentID is the Firestore document's reference that we get from the module FirebaseFirestoreSwift.

View Model

Let’s now use this model and make a connection with the Firebase backend. We are going to implement all the functions in the View Model.

Create a new Swift file and call it NoteViewModel,

Then, copy/paste the following code:

Here, we have done a couple of things:

  • First, we made a reference to our Model, we created earlier.
  • We made a reference to the Firestore database collection, we will use this path to post, read, update and delete data.
  • We implement the function to post the data to cloud firestore, passing a String (the title).
  • We add a listener to fetch all documents under the Firestore collection “Notes”.
  • We add the function to update the String of the selected document.
  • Finally we add the function to delete data based on the indexSet, this will allow us to remove the data from both our List and erase it from the database.

We have everything to create our user interface now.

View

Our user interface will be compose of a List which will allow us to delete a row and navigate to another screen. From there you can also edit it.

You will also be able to post a note trough an alert with a textField.

Heads to the contentView.swift file, first make a reference to our View Model:

@ObservedObject private var viewModel = NoteViewModel()

Read data

Then heads the body variable and implement a SwiftUI List embed in a NavigationStack:

Post data

Great! We just implemented a List that fetch data from Firestore in real time. Let’s post some data now, in the same file, add the followings two States:

@State private var presentAlert = false@State private var titleText: String = “”

This will allow us to present and close an alert and read user’s input from the TextField.

Now, add the following code right under your List:

This toolBar which contains a button to present an alert with a text entry will allow us to post data to Firestore, you can now go ahead and write a few:

2 screenshots of an iPhone presenting an alert and a list
Screenshots of our application running

It also contains a text to present how many notes are written (with the .count key).

Now that we are able to read and post notes thanks to the great APIs of Firestore, let’s try to update these notes.

Passing Data

Before updating the data, we will first implement a DetailsView, from there, we will edit our document.

Go ahead and create a new SwiftUI View, call it DetailsView, then integrate the following code:

Then, go back to the ContentView.swift file and replace your current List with this one:

This will allow us to navigate from one view to another while passing data with NavigationLink.

Update data

For updating the data, we will first implement another toolBarItem with an alert, from there we will allow the user to enter a new text.

First, let’s observe the followings states at the top of DetailsView.swift:

@State private var presentAlert = false@State private var titleText: String = ""@ObservedObject private var viewModel = NoteViewModel()

With these states, we are linking to the View Model to pass data to Firestore, handling alert presentation and managing the text entry. We can now integrate our toolbar, copy/paste the code below right we we left a comment for the toolbar:

You can now run your application, navigate between views and update your notes to Firestore by clicking on “edit” and entering a new text.

Delete data

Last step, delete our notes, this one is simple, SwiftUI is handling everything with the List modifier, add the following onDelete modifier in the ContentView.swift file:

List {      ForEach(viewModel.notes, id:\.id) { Note in        NavigationLink(destination: DetailsView(note: Note)) {          VStack(alignment: .leading) {            Text(Note.title ?? "").font(.system(size: 22, weight: .regular))       }.frame(maxHeight: 200)    }  }.onDelete(perform: self.viewModel.deleteData(at:)) }.onAppear(perform: self.viewModel.fetchData) .navigationTitle("Notes")

You can now swift right on any list row, click on delete, this will delete the data from Firestore and remove it from the list indexes at the same time.

Conclusion

With this exercice, we learn how to connect our application to Firebase Firestore, create, read, update and delete data to and from the database. We also use the Model, View, View-Model to better organise our codebase.

I’m always happy to have a chat and collaborate at hello@sullivandecarli.com. Consider subscribing to enjoy unlimited access to my articles and all of Medium through my referral link.

--

--

Sullivan De Carli
Swift Productions

Consultant in iOS Dev at Deloitte. I write about Design & App development. Let’s have a chat at hello@sullivandecarli.com