I have a map based app so I want to have an app-wide property for the current position of the map.
I'm initializing it in SceneDelegate
let currentPosition = CurrentPosition()
let mainView = MainView(appState: AppState(), selectedWeatherStation: nil).environmentObject(currentPosition)
I have it declared in MainView
as an @EnvironmentObject
struct MainView: View {
@State var appState: AppState
@State var selectedWeatherStation: WeatherStation? = nil
@EnvironmentObject var currentPosition: CurrentPosition
and I inject it into my UIViewRepresentable
child
MapView(weatherStations: $appState.appData.weatherStations,
selectedWeatherStation: $selectedWeatherStation).environmentObject(currentPosition)
.edgesIgnoringSafeArea(.vertical)
in MapView
struct MapView: UIViewRepresentable {
@Binding var weatherStations: [WeatherStation]
@Binding var selectedWeatherStation: WeatherStation?
@EnvironmentObject var currentPosition: CurrentPosition
i have a final subclass
final class Coordinator: NSObject, MKMapViewDelegate {
@EnvironmentObject var currentPosition: CurrentPosition
which acts as my mapview delegate, where I want to update the currentPosition
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
currentPosition = CurrentPosition(northEast: mapView.northEastCoordinate, southWest: mapView.southWestCoordinate)
}
But this assignament
currentPosition = CurrentPosition(northEast: mapView.northEastCoordinate, southWest: mapView.southWestCoordinate)
will throw an error
Cannot assign to property: 'currentPosition' is a get-only property
and I really have no idead what I'm doing wrong.
The purpose is to update the position each time the user moves the map so I can perform a request to my API with the current coordinates.
CurrentPosition is declared as follows
class CurrentPosition: ObservableObject {
@Published var northEast = CLLocationCoordinate2D()
@Published var southWest = CLLocationCoordinate2D()
init(northEast: CLLocationCoordinate2D = CLLocationCoordinate2D(), southWest: CLLocationCoordinate2D = CLLocationCoordinate2D()) {
self.northEast = northEast
self.southWest = southWest
}
}