Hi, I tried the following code from a short tutorial about CoreLocation / LocationButton
From the code, I would have expected the call associated with the LocationButton to return a new (refreshed) set of coordinates every time the button is tapped, but if I tap the button and move to a new location, I keep getting the initial value of the coordinates:
- Am I interpreting the code wrong?
- Perhaps the GPS on a phone is just not as sensitive as I thought a priori and the readings just appear not to change in a small displacement?
import SwiftUI
import CoreLocation
import CoreLocationUI
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
@Published var location: CLLocationCoordinate2D?
override init() {
super.init()
manager.delegate = self
}
func requestLocation() {
manager.requestLocation()
//print("Requesting Location")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location = locations.first?.coordinate
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error requesting location")
}
}
struct ContentView: View {
@StateObject var locationManager = LocationManager()
var body: some View {
VStack {
if let location = locationManager.location {
Text("Your location: \(location.latitude), \(location.longitude)")
}
LocationButton {
locationManager.requestLocation()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}