How To Use Firebase Firestore in Swift & SwiftUI

How to Use Firebase Firestore in Swift & SwiftUI

Firebase Firestore is a powerful NoSQL cloud database that can be used to store and sync data across multiple platforms. It is a great choice for developing mobile applications due to its scalability, reliability, and ease of use. In this tutorial, you will learn how to use Firebase Firestore in your Swift and SwiftUI apps to read and write data. We will build a basic todo app, so you can learn all the necessary steps to get up and running with Firebase Firestore.

Setting up the iOS App in Swift & SwiftUI

We will start by setting up a basic iOS app with SwiftUI. If you already have an existing project, you can skip this section.

  1. Open Xcode and create a new project.
  2. Select the Single View App template and click Next.
  3. Enter a product name, such as TodoApp, and make sure the User Interface is set to SwiftUI.
  4. Click Next and save the project in a folder of your choice.

Adding All Firebase Dependencies

Next, we will add all the necessary Firebase dependencies.

  1. Open your project in Xcode and select the TodoApp project in the Project Navigator.
  2. Select your TodoApp target, then click Signing & Capabilities.
  3. Click the + Capability button and select Firebase.
  4. Select the Firebase/Core checkbox and click Next.
  5. Select the Firebase/Firestore checkbox and click Finish.

Setting up Firestore Read and Write Access Rules

We need to set up the read and write access rules for our Firestore database.

  1. Log in to the Firebase Console.
  2. Select your project and click the Database tab.
  3. Click the Rules tab and set the read and write rules to true.
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Writing to Firestore from Swift

Now that our project is set up, we can start writing data to Firestore.

  1. Open ContentView.swift and add the following code at the top of the file:
import FirebaseFirestore

// Reference to Firestore
let db = Firestore.firestore()

This code imports the FirebaseFirestore module and creates a reference to our Firestore database.

  1. Add the following code to the createTodo() method:
// Create a document in the todos collection
db.collection("todos").addDocument(data: [
    "title": title,
    "completed": false
])

This code creates a new document in the todos collection with the title and completed status.

Reading Single Objects from Firestore

We can also read single objects from Firestore.

  1. Add the following code to the readTodo() method:
// Read a single document from the todos collection
db.collection("todos").document(id).getDocument { (document, error) in
    if let document = document {
        let title = document.data()?["title"] as? String
        let completed = document.data()?["completed"] as? Bool
    }
}

This code reads a single document from the todos collection and stores the title and completed status in variables.

Reading & Displaying Lists of Objects

We can also read and display lists of objects from Firestore.

  1. Add the following code to the readTodos() method:
// Read all documents from the todos collection
db.collection("todos").getDocuments { (snapshot, error) in
    if let snapshot = snapshot {
        for document in snapshot.documents {
            let title = document.data()["title"] as? String
            let completed = document.data()["completed"] as? Bool
        }
    }
}

This code reads all documents from the todos collection and stores the title and completed status in variables.

  1. Add the following code to the ContentView struct:
@State private var todos: [Todo] = []

var body: some View {
    List(todos, id: \.id) { todo in
        Text(todo.title)
    }
}

This code displays the list of todos in the SwiftUI view.

Listening to Real-Time Updates

We can also listen for real-time updates from Firestore.

  1. Add the following code to the listenToTodos() method:
// Listen for real-time updates from the todos collection
db.collection("todos").addSnapshotListener { (snapshot, error) in
    if let snapshot = snapshot {
        for document in snapshot.documents {
            let title = document.data()["title"] as? String
            let completed = document.data()["completed"] as? Bool
        }
    }
}

This code listens for real-time updates from the todos collection and stores the title and completed status in variables.

Batch Updates to Improve Performance

We can also use batch updates to improve the performance of our Firestore requests.

  1. Add the following code to the updateTodos() method:
// Create a batch for updating multiple documents
let batch = db.batch()

// Update each document in the batch
for todo in todos {
    let ref = db.collection("todos").document(todo.id)
    batch.updateData(["completed": true], forDocument: ref)
}

// Commit the batch
batch.commit { (error) in
    // Handle any errors
}

This code creates a batch for updating multiple documents and commits the batch.

How to Paginate Lists from Firestore

We can also paginate lists from Firestore.

  1. Add the following code to the readTodos() method:
// Read documents from the todos collection with pagination
db.collection("todos").limit(to: 10).getDocuments { (snapshot, error) in
    if let snapshot = snapshot {
        for document in snapshot.documents {
            let title = document.data()["title"] as? String
            let completed = document.data()["completed"] as? Bool
        }
    }
}

This code reads documents from the todos collection with pagination.

Conclusion

In this tutorial, you learned how to use Firebase Firestore in your Swift and SwiftUI apps. We built a basic todo app, so you can learn all the necessary steps to get up and running with Firebase Firestore. You learned how to write and read data, listen for real-time updates, batch updates to improve performance, and paginate lists from Firestore.