0
0
iOS Swiftmobile~5 mins

Cloud Firestore in iOS Swift

Choose your learning style9 modes available
Introduction

Cloud Firestore helps your app save and get data from the cloud easily. It keeps your data safe and up to date on all devices.

You want to save user settings or preferences online.
You need to show live updates like chat messages or scores.
You want to store app data that many users can access.
You want to sync data between a phone and a tablet automatically.
Syntax
iOS Swift
import FirebaseFirestore

let db = Firestore.firestore()

// To add data:
db.collection("users").addDocument(data: ["name": "Alice", "age": 25])

// To read data:
db.collection("users").getDocuments { snapshot, error in
  if let snapshot = snapshot {
    for document in snapshot.documents {
      print(document.data())
    }
  }
}
Use Firestore.firestore() to get the database instance.
Collections hold documents, and documents hold data as key-value pairs.
Examples
Adds a new message with text "Hello!" to the messages collection.
iOS Swift
db.collection("messages").addDocument(data: ["text": "Hello!"])
Sets or updates the document with ID "user123" in users collection.
iOS Swift
db.collection("users").document("user123").setData(["name": "Bob"])
Reads all documents from users collection and prints their data.
iOS Swift
db.collection("users").getDocuments { snapshot, error in
  if let snapshot = snapshot {
    for doc in snapshot.documents {
      print(doc.data())
    }
  }
}
Sample App

This SwiftUI app shows a list of messages from Firestore. When you tap the button, it adds a new message. The list updates live when messages change.

iOS Swift
import SwiftUI
import Firebase
import FirebaseFirestore

struct ContentView: View {
  @State private var messages: [String] = []
  let db = Firestore.firestore()

  var body: some View {
    VStack {
      List(messages, id: \.self) { msg in
        Text(msg)
      }
      Button("Add Message") {
        db.collection("messages").addDocument(data: ["text": "Hi from SwiftUI!"])
      }
    }
    .onAppear {
      db.collection("messages").addSnapshotListener { snapshot, error in
        if let snapshot = snapshot {
          messages = snapshot.documents.compactMap { $0.data()["text"] as? String }
        }
      }
    }
  }
}
OutputSuccess
Important Notes

Remember to set up Firebase in your Xcode project before using Firestore.

Firestore updates data live, so your app stays in sync automatically.

Use addSnapshotListener to listen for real-time updates.

Summary

Cloud Firestore stores app data in the cloud and syncs it live.

Use collections and documents to organize your data.

Firestore works well for apps that need live updates and shared data.