Getting error when trying to change location Authorisation

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
            }
        }
    }

}

What tutorial are you trying to copy with this? Have you checked out the materials/source code to check for similarities?

I’m following this tutorial, SwiftUI 2.0 MapKit - iOS 14 Precise Locations - SwiftUI 2.0 Maps - SwiftUI Core Location - YouTube

But I have made some minor changes and so. I have checked for similarities.

But if you dont tamper with the permissions on the settings page its all good?