Seb
Seb

Reputation: 3215

SwiftUI location permission does not show up

I am trying to check the location permission on my app, but the app does not display the pop-up with all the options like "Always", "Only when using the app" or "never"

I am doing it when clicking on a buttom like below:

Button(action: {
                LocationManager.shared.requestLocationAuthorization()
                print("click to current" + searchText)
               }) {
               Text("Current Location)
            }

and then I am using the class below:

class LocationManager: NSObject, CLLocationManagerDelegate {

    static let shared = LocationManager()
    private var locationManager: CLLocationManager = CLLocationManager()
    private var requestLocationAuthorizationCallback: ((CLAuthorizationStatus) -> Void)?

    public func requestLocationAuthorization() {
        self.locationManager.delegate = self
        let currentStatus = CLLocationManager.authorizationStatus()

        // Only ask authorization if it was never asked before
        guard currentStatus == .notDetermined else { return }

        if #available(iOS 13.4, *) {
            self.requestLocationAuthorizationCallback = { status in
                if status == .authorizedWhenInUse {
                    self.locationManager.requestAlwaysAuthorization()
                }
            }
            self.locationManager.requestWhenInUseAuthorization()
        } else {
            self.locationManager.requestAlwaysAuthorization()
        }
    }
    public func locationManager(_ manager: CLLocationManager,
                                didChangeAuthorization status: CLAuthorizationStatus) {
        self.requestLocationAuthorizationCallback?(status)
    }
}

Whatever I am doing, the pop to ask the user is not popping up.

the button is called in a VStack.

Thanks for your help

Upvotes: 1

Views: 3334

Answers (1)

federicoramos77
federicoramos77

Reputation: 168

Are the correct keys in your info.plist?

<key>NSLocationUsageDescription</key>
<string>Your description here</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Your description here</string>

According to Apple, if these keys are missing.

Important You must add the required keys to your app’s Info.plist file. If a required key isn’t present, authorization requests fail immediately.

Source: https://developer.apple.com/documentation/corelocation/requesting_authorization_for_location_services

Upvotes: 2

Related Questions