'Swift code is reading Firestore DB using addSnapshotListener but no snapshot or error is created
I have some very simple data in Firestore I am trying to read into my iOS app. There is one collection called "matches" with one document containing two fields "id" and "name".
With the code below I am trying to load the Firestore data into my array of matches, but it is not working. I can see in the Firestore usage data that the DB is being read, but no data is being saved to the local variables. Upon execution of this code I expected the matches array to have one object, but it remains empty. When I debug the code line by line, nothing is executing after this line:
collection.addSnapshotListener { (querySnapshot, error) in
Which to me indicates no snapshot or error are being produced, but I don't know why.
Full code:
import Foundation
import Firebase
class ContentModel: ObservableObject {
let db = Firestore.firestore()
// List of matches
@Published var matches = [Match]()
init() {
// Get database matches
getMatches()
}
func getMatches() {
// Specify path
let collection = db.collection("matches")
// Get documents
collection.addSnapshotListener { (querySnapshot, error) in
print("test") // this print statement never executes
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
}
}
}
}
The ContentModel is instantiated in the main .swift file for the project as an environment object. Code below:
import SwiftUI
import Firebase
@main
struct AppName: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
MatchTabView().environmentObject(ContentModel())
}
}
}
Solution 1:[1]
Found the issue. The view was loading before the data could be read into my array. I'm not sure why the code is not executed when initially debugged, but the data is be read in once I added error handling so the view can load without data.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dilly |
