TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Getting error when trying to change location Authorisation

Forums > SwiftUI

Hi, I currently have this code where I get the user's current location and then display it on a map. And this seems to work fine. But when the user presses "Allow while in use" and then goes into settings and changes it to "Ask next time" my app crashes. And when that happens I get the following error(s)

Error: The operation couldn’t be completed. (kCLErrorDomain error 1.)

And

CLLocationManager(<CLLocationManager: 0x600001d84740>) for <MKCoreLocationProvider: 0x600002d803f0> did fail with error: Error Domain=kCLErrorDomain Code=1 "(null)"

I don't have a lot of experience but I suspect the issue is due to line 3. I think I'm supposed to use @StateObject. But I could be completely wrong.

If its not line 3 it could be from where I have commented Checking authorization status... and down. But honestly I don't know

Any ideas on what the problem is?

Btw I have added all the necessary "things" to my info.plist

struct Home: View{

    @State var tracking : MapUserTrackingMode = .follow

     // This line could be the issue
    @State var manager = CLLocationManager()

    @StateObject var managerDelegate = locationDelegate()

    var body: some View {
        VStack{

            Map(coordinateRegion: $managerDelegate.region, interactionModes: .all, showsUserLocation: true, userTrackingMode: $tracking, annotationItems: managerDelegate.pins) { pin in
                MapPin(coordinate: pin.location.coordinate, tint: .red)

            }.edgesIgnoringSafeArea(.all)
        }.onAppear{
            manager.delegate = managerDelegate
            manager.distanceFilter = kCLDistanceFilterNone
            print("On Appear")
            manager.desiredAccuracy = kCLLocationAccuracyBest
            manager.activityType = .automotiveNavigation

        }
        .alert(isPresented: $managerDelegate.locationPermissionDenied, content: {
            Alert(title: Text("Permission Denied"),
                  message: Text("Please Enable Permission In App Settings"),
                  dismissButton: .default(Text("Go To Settings"),
                                          action: {
                                            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
                  }))
        })
    }
}

class locationDelegate: NSObject,ObservableObject,CLLocationManagerDelegate{

    @Published var pins : [Pin] = []

    @Published var location: CLLocation?

    @State var hasSetRegion = false

    @Published var locationPermissionDenied = false

    @Published var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 38.898150, longitude: -77.034340),
        span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
    )

    // Checking authorization status...

    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {

        switch manager.authorizationStatus {

        case .denied :
            // Alert
            locationPermissionDenied = true
            print("Denied")
            print(locationPermissionDenied)

        case .restricted:
            print("restricted")

        case .notDetermined:
            // Request
            print("not Determined")
            manager.requestWhenInUseAuthorization()

        case .authorizedWhenInUse :
            print("Authorized when in use")
            manager.allowsBackgroundLocationUpdates = true
            manager.startUpdatingLocation()

        default:
            print("Default")
        }

    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error : Error){
        print("Error: \(error.localizedDescription)")
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // pins.append(Pin(location:locations.last!))

        if let location = locations.last {
            print("Latitude: \(location.coordinate.latitude)")
            print("Longitude: \(location.coordinate.longitude)")
            self.location = location

            if hasSetRegion == false{
                region = MKCoordinateRegion(center: location.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.001, longitudeDelta: 0.001))
                hasSetRegion = true
            }
        }
    }

}

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.