Here is the full error:
`Fatal error: No ObservableObject of type LocationsViewModel found. A View.environmentObject(_:) for LocationsViewModel may be missing as an ancestor of this view.`
I am essentially creating an app. The user can login/register. Once the user logs in they see a map view (MapKit). Here is just the main code (excluding the login/register parts). Any idea what i am doing wrong?
// MARK: MAP SCREEN
struct UserScreen: View {
@Binding var sucessLogin : Bool
@StateObject private var vm = LocationsViewModel()
var body: some View{
ZStack{
Map(coordinateRegion: $vm.mapRegion)
.ignoresSafeArea()
VStack(spacing: 0){
VStack{
Button(action: vm.toggleLocationsList){
Text(vm.mapLocation.name + ", " + vm.mapLocation.cityName)
.font(.title2)
.fontWeight(.black)
.foregroundColor(.white)
.frame(height: 55)
.frame(maxWidth: .infinity)
.background(Color("Theme"))
.overlay(alignment: .leading){
Image(systemName: "arrow.down")
.font(.headline)
.foregroundColor(.white)
.padding()
}
}
if vm.showLocationsList{
LocationsListView()
}
}
.background(.thickMaterial)
.cornerRadius(10)
.shadow(color: Color.black.opacity(0.3), radius: 20, x: 0, y: 15)
.padding()
Spacer()
}
}
.navigationTitle("")
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
}
}
I then have a LocationsViewModel which is in a different SwiftUI View file because I have a custom dropdown menu, here is the code:
// MARK: MAP Screen ViewModel
class LocationsViewModel: ObservableObject{
@Published var locations: [Location]
@Published var mapLocation: Location{
didSet{
updateMapRegion(location: mapLocation)
}
}
//Show current region on map
@Published var mapRegion: MKCoordinateRegion = MKCoordinateRegion()
let mapSpan = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
// Show list of locations
@Published var showLocationsList: Bool = false
init(){
let locations = LocationsDataService.locations
self.locations = locations
self.mapLocation = locations.first!
self.updateMapRegion(location: locations.first!)
}
private func updateMapRegion(location: Location){
withAnimation(.easeInOut){
mapRegion = MKCoordinateRegion(
center: location.coordinates,
span: mapSpan)
}
}
func toggleLocationsList(){
withAnimation(.easeInOut){
showLocationsList.toggle()
}
}
}
Not sure what the error means and how I can fix it, because in my ViewModel i have it extended to Observable Object.
If you would like I can also provide a GitHub link to my project.