I want to have a swift func() that takes a documentID and returns the corresponding document. I want this func() to use async/await and provide realtime updates whenever the document is modified by others.
The following document snippet from firestore doco, works fine for me when I have the code hard coded within the .task {} area of my view but I want it to be called as a func() that resides in my viewmodel.
Here is the code snippet from Firebase doco.
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)")
}
But here is what I'm trying to do... I'm getting loads of errors with this.
//
// example: fetching a single object with a listener
//
func fetchCityWithListener(documentID: String) async throws -> City {
db.collection("cities").document(documentID)
.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)")
let city = try? Firestore.Decoder().decode(City.self, from: data)
return city
}
}
My intent is to call the function like this...
// example: call to get a single object with a listener on it
//
Task {
do {
city = try await cityViewViewModel.fetchCityWithListener(cityID: "atlanta")
// Handle the fetched city
} catch {
// Handle the error
print("Error: \(error) - skljle88")
}
}