user10166622
user10166622

Reputation:

How can I use the addSnapshotListener method with getDocument when writing to Firestore in Swift?

I am trying to fetch data from Firebase Firestore. I am successful in fetching the data, however, I am displaying it in a UITableView and I need it to fetch it in real-time. I am using the getDocuments method and I cannot add a snapshot listener because I cannot write over the getDocuments arguments.

func loadPartiesDataFromFirebase() {
    let db = Firestore.firestore()
    db.collection("parties").getDocuments() { snapshot, err in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in (snapshot!.documents) {
                let title = document.data()["title"] as? String ?? "New Party"
                let location = document.data()["location"] as? String ?? "No Location"
                let date = document.data()["date"] as? String ?? "No Date"
                let startTime = document.data()["startTime"] as? String ?? "No Start Time"
                let endTime = document.data()["endTime"] as? String ?? "No End Time"

                self.parties.append(Party(title: title, location: location, date: date, startTime: startTime, endTime: endTime))
            }
        }

        self.yourPartiesTableView.reloadData()
}

I wanted it to continuously display the data from Firestore in real-time. How can I do that in Swift?

Upvotes: 0

Views: 2049

Answers (1)

denys
denys

Reputation: 31

You need to add a listener to the collection.

    let db = Firestore.firestore()
    let listener = db.collection("parties").addSnapshotListener { (snapshot, error) in
        switch (snapshot, error) {
        case (.none, .none):
            print("no data")
        case (.none, .some(let error)):
            print("some error \(error.localizedDescription)")
        case (.some(let snapshot), _):
            print("collection updated, now it contains \(snapshot.documents.count) documents")
        }
    }

Also, you can store a reference to your listener and the remove it when you don't need it.

    listener.remove()

Upvotes: 2

Related Questions