Learn Courses My Dashboard

Code is Reading Firestore DB but no snapshot or error created

I’m using a modified version of the code from The Learning App module to pull in data from my Firestore DB. I can see in the Firestore usage data that this code is reading the DB, but no data is being loaded to my local variables. When I debug the code, it completely skips all code after this line:

collection.addSnapshotListener { (querySnapshot, error) in

I think indicating that no querySnapshot or error is being produced? Anyone know what is going on here?

Here is the relevant code:

ContentModel.swift

import Foundation
import Firebase

class ContentModel: ObservableObject {
    
    let db = Firestore.firestore()
    
    // List of matches
    @Published var matches = [Match]()

init() {
        
        // Get golf matches from DB
        getMatches()
        
    }

func getMatches() {
        
        // Specify path
        let collection = db.collection("matches")
        
        // Get documents
        collection.addSnapshotListener { (querySnapshot, error) in // debugger skips everything after this
           
            if let error = error {
                print("Error retrieving collection: \(error)")
            }
            else {
                
                // Create an array for the matches
                var matches = [Match]()
                
                // Loop through the documents returned
                for doc in querySnapshot!.documents {
                    
                    // Create a new Match instance
                    var m = Match()
                    
                    // Parse out the values from the document into the Match instance
                    m.id = doc["id"] as? String ?? UUID().uuidString
                    m.name = doc["name"] as? String ?? ""
                                                 
                    // Add it to our array
                    matches.append(m)
                }
                
                // Assign our matches to the published property
                DispatchQueue.main.async {
                    
                    self.matches = matches
                }
            }
            
        }
        
    }

And here is the very simple Struct Match for reference:

struct Match: Decodable, Identifiable {
    
    var id: String = ""
    var name: String = ""
}
1 Like

Can I please see a picture of your Firestore?

I ended up hiring a developer to look at it. The issue was the view was loading and calling for data before it had loaded from Firestore, and I didn’t have any error handling. Once I handled the case where data didn’t exist yet it began functioning normally.

1 Like