My app has a problem updating location after resetting location service to enable. So when the system location service is enabled, my app has no problem updating the location. But if I closed the app and disabled the system location service, then restart the app, it will show an alert to enable the system location service. After enabling location service, then going back to the app, its location has no updating at all. I have the longitude, latitude, heading..etc UIs to indicate whether the location is updated or not. Here are my view's code and location manager class, could someone help me out? Thanks
View
struct ContentView: View {
@StateObject private var locationManager = LocationManager()
@State var trackingInfo = ARViewContainer.TrackingInfo()
@State var isLocationServiceOff = false
var body: some View {
ZStack {
ARViewContainer(trackingInfo: $trackingInfo)
.edgesIgnoringSafeArea(.all)
.onAppear{
if CLLocationManager.locationServicesEnabled() {
locationManager.checkIfLocationServicesIsEnabled()
} else {
isLocationServiceOff = true
}
}
.alert(isPresented: $isLocationServiceOff) {
Alert(title: Text("Location Service Disabled"),
message: Text("Geospatial experience requires location service enabled"),
primaryButton: .default(Text("Setting")){
if #available(iOS 10.0, *) {
if let url = URL(string: "App-Prefs:root=Privacy&path=LOCATION") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
} else {
if let url = URL(string: "prefs:root=LOCATION_SERVICE") {
UIApplication.shared.open(url)
}
}
}, secondaryButton: .cancel(Text("Cancel")))
}
}
}
}
}
LocationManager
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
//User could turn location service off, so it's an optional.
var locationManager: CLLocationManager?
func checkIfLocationServicesIsEnabled() {
if CLLocationManager.locationServicesEnabled() {
locationManager = CLLocationManager()
locationManager!.delegate = self
}
}
private func checkLocationAuthorization() {
guard let locationManager = locationManager else {
return
}
switch locationManager.authorizationStatus {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .restricted:
print("Restricted location services due to parental controls")
case .denied:
print("You have denied this app location permission. Go into settings to change it")
case .authorizedAlways, .authorizedWhenInUse:
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.allowsBackgroundLocationUpdates = true
@unknown default:
break
}
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
checkLocationAuthorization()
}
}