firebasegoogle-cloud-firestoreswiftuichatmessage

How to listen for realtime updates using FirebaseFirestore within SwiftUI app


How to listen for realtime updates using FirebaseFirestore within SwiftUI app.


Solution

  • What you're looking for is called a snapshot listener. Effectively it's treated the same as with any other documents but it has a closure that allows you to respond to updated events on a particular document. It's general usage is this.

    db.collection("cities").document("SF")
    .addSnapshotListener { documentSnapshot, error in
      guard let document = documentSnapshot else {
        print("Error fetching document: \(error!)")
        return
      }
      guard let data = document.data() else {
        print("Document data was empty.")
        return
      }
      print("Current data: \(data)")
    }
    

    You should be able to look at the document snapshot to determine any changes in data, then respond to those changes. In your case you would reload the view.

    https://firebase.google.com/docs/firestore/query-data/listen