Search code examples
iosswiftswiftuilocationcore-location

Swift locationManager.requestWhenInUseAuthorization() not prompting the user


locationManager.requestWhenInUseAuthorization()

is called when the user pushes a button, but no prompt is displayed.

Here is my full code

import SwiftUI
import CoreLocation



struct ContentView: View {
    @ObservedObject var distanceTracker = DistanceTracker();
    var body: some View {

        Button(action: distanceTracker.enableLocServices){
            Text("Enable Location")
        }
        
    }


}



struct ContentView_Previews: PreviewProvider {

    static var previews: some View {

        ContentView()

    }

}


import CoreLocation

class DistanceTracker: NSObject, ObservableObject, CLLocationManagerDelegate {
    
    let locationManager = CLLocationManager()
    var startLocation: CLLocation!
    var lastLocation: CLLocation!
    @Published var traveledDistance = 0.0
    
    override init() {
        super.init()
        locationManager.delegate = self
    }
    
    func enableLocServices(){
        locationManager.requestWhenInUseAuthorization()
        print("bruh")
    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        switch manager.authorizationStatus {
        case .notDetermined:
            print("Location permission not asked for yet")

        case .restricted:
            print("Location usage is restricted (perhaps by parental controls or some other restriction)")
        case .denied:
            print("Location permission denied by user")
        case .authorizedAlways:
            print("Location permission granted for background and foreground use")
        case .authorizedWhenInUse:
            print("Location permission granted for foreground use only")
        @unknown default:
            print("An unknown authorization status received")
        }
    }
}

On button press, it prints "bruh". Edit: Also, the status printed is "Location permission not asked for yet"

NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription are both added to the info section. enter image description here

Location services on both the watch and phone are enabled (this is a watchOS only app but still, and I couldn't get this to work for IOS anyway), and the permission was not previously denied. How can I fix this? Thanks!


Solution

  • You are using this

    Privacy - Location Always and When In Use Usage Description
    

    You need to add also this:

    Privacy - Location When In Use Usage Description
    

    When you try with this you will see permission pop up.