0
votes

I am trying to create a Listener for changes to a Document. When I change the data in Firestore (server) it doesn't update in the TableView (App). The TableView only updates when I reopen the App or ViewController.

I have been able to set this up for a Query Snapshot but not for a Document Snapshot.

Can anyone look at the code below to see why this is not updating in realtime?

    override func viewDidAppear(_ animated: Bool) {

    var newDocIDString = newDocID ?? ""


    detaliPartNumberListerner = firestore.collection(PARTINFO_REF).document(newDocIDString).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)")
        self.partInfos.removeAll()
        self.partInfos = PartInfo.parseData2(snapshot: documentSnapshot)
        self.issueTableView.reloadData()

    }

In my PartInfo file

    class func parseData2(snapshot: DocumentSnapshot?) -> [PartInfo] {
    var partNumbers = [PartInfo]()


    guard let snap = snapshot else { return partNumbers }
    //for document in snap.documents {
      //  let data = document.data()

        let area = snapshot?[AREA] as? String ?? "Not Known"

        let count = snapshot?[COUNT] as? Int ?? 0


        //let documentId = document.documentID
    let documentId = snapshot?.documentID ?? ""

        let newPartInfo = PartInfo(area: area, count: count, documentId: documentId)

        partNumbers.append(newPartInfo)

    return partNumbers
}
1
Can you describe what you see from the logging in your code, and when? Do you see "Current Data..." when the vc first appears and then again when the data is updated?danh
Have you put a breakpoint in the observer block?Niamh
Hi Lara, It is an issue with my tableView. When I make changes through Firestore (server) the listener captures the data and displays this in print code. It is not updating my TableView. It is only when I go back 1 View and renter the view that it updatesS.MacPherson
Apologises, I've created a variable in ViewDidLoad and used this in cellForRowAt So my changes will never get called. I still haven't tested this to see if it works but I'm certain it will.S.MacPherson
Actually, this hasn't made any difference. It still doesn't update my TableView...S.MacPherson

1 Answers

0
votes

UI work must always be done on the main thread. So instead of your last line in your first code snippet, do this:

DispatchQueue.main.async {
    self.issueTableView.reloadData()
}

I think this might be the solution to your problem. (A little late, I know ...)