I just want to ask my user for a one-time location permission. However, when I click the button that activates the permission dialog, it disappears after one second.
This has been brought up before - however I am already following this advice and storing @ObservedObject var locationManager = LocationManager() as a class variable in my view.
View
Model
Any idea what the problem is?
This has been brought up before - however I am already following this advice and storing @ObservedObject var locationManager = LocationManager() as a class variable in my view.
View
Code Block struct Login: View { @EnvironmentObject var sessionManager: SessionManager @ObservedObject var locationManager = LocationManager() var body: some View { NavigationView { VStack { Section { Button(action: { locationManager.requestPermission() }){ Text("Verify location") } }
Model
Code Block class LocationManager: NSObject, ObservableObject , CLLocationManagerDelegate { @Published var locationStatus: CLAuthorizationStatus? = CLAuthorizationStatus.notDetermined @Published var locationPermissionStatus = PermissionStatus.unknown @Published var location: CLLocation? let locationManager = CLLocationManager() override init(){ super.init() self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest } func requestPermission(){ print("Request permissions") self.locationManager.requestWhenInUseAuthorization() } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .restricted, .denied: locationPermissionStatus = PermissionStatus.denied break case .authorizedWhenInUse: locationPermissionStatus = PermissionStatus.authorizedWhenInUse self.locationManager.startUpdatingLocation() break case .authorizedAlways: locationPermissionStatus = PermissionStatus.authorizedAlways self.locationManager.startUpdatingLocation() break case .notDetermined: locationPermissionStatus = PermissionStatus.unknown break } } func denyPermission(){ self.locationPermissionStatus = PermissionStatus.denied } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } self.location = location } enum PermissionStatus { case unknown case authorizedWhenInUse case authorizedAlways case restricted case denied } func getLocation() -> CLLocationCoordinate2D? { return self.location?.coordinate } }
Any idea what the problem is?