I am trying to pass an array of values retrieved from Firebase into a View. However, the array passed into the View is empty when there should be values within the array.
This is the model I've created. eventLocations is the property that I want to pass into my View.
class FoodEventViewModel: ObservableObject {
@Published var foodEvents = [FoodEvent]()
@Published var eventLocations = [CLLocationCoordinate2D]()
private var db = Firestore.firestore()
var events = [FoodEvent?]()
init() {
getLocations()
}
func fetchData() {
let ref = db.collection("Food Submissions").order(by: "dateCreated", descending: true)
ref.addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("No documents")
return
}
self.events = documents.map { (queryDocumentSnapshot) -> FoodEvent? in
let event = try? queryDocumentSnapshot.data(as: FoodEvent.self)
return event
}
}
foodEvents = events.compactMap { $0 }
}
func getLocations() {
fetchData()
for event in foodEvents {
let coord = CLLocationCoordinate2D(latitude: event.latitude,
longitude: event.longitude)
eventLocations.append(coord)
}
}
}
I must be misunderstanding how data flows between views and models. Is there a way to make sure that my view receives a populated array? I've tried to use ObservableObject and EnvironmentObject to pass data to the view. I've tried to use .onAppear { viewModel.getLocations } but the view still has an empty array.
struct FoodMapView: View {
@EnvironmentObject var lm: LocationManager
@ObservedObject var viewModel = FoodEventViewModel()
var body: some View {
ZStack(alignment: .top) {
MapView(locs: viewModel.eventLocations)
.onAppear {
viewModel.getLocations()
print("Map View")
print(viewModel.eventLocations)
}
}.navigationTitle("Map")
}
}
Any help would be greatly appreciated!