I have a location manager class that looks like this:
final class LocationManager: NSObject, ObservableObject {
var location: CLLocation?
@Published var authorizationStatus: CLAuthorizationStatus
@Published var totalDistance: CGFloat
@Published var locationData: String
private let locationManager: CLLocationManager
...
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let latestLocation = locations.last else { return }
DispatchQueue.main.async {
if let currentLocation = self.location {
let distance = latestLocation.distance(from: currentLocation)
self.totalDistance += distance
self.location = latestLocation
self.locationData = String(format: "%.5f", latestLocation.coordinate.latitude) + ", " + String(format: "%.5f", latestLocation.coordinate.longitude)
print("location: \(self.locationData), distance: \(self.totalDistance)") //I see coordinates continuously printed here, so I know the location data is getting updated
} else {
self.location = latestLocation
}
}
}
}
Then, I have a view model that has this:
@ObservedObject var locationManager : LocationManager //I tried @Published here too, to no avail.
init() {
let localLocationManager = LocationManager()
self.locationManager = localLocationManager
}
And a view like this:
@EnvironmentObject var viewModel: MyViewModel
...
VStack {
Text("TEST DATA")
Text("Location: \(viewModel.locationManager.locationData)")
Text("distance traveled: \(viewModel.locationManager.totalDistance)")
}
However none of this text gets updated when the user's location changes. What am I missing? Other @Published properties in my view model do cause the view to update.