wade-watt wade-watt - 3 months ago 8
iOS Question

iOS App Location Permission is not Working Currently

It is my general ViewController class , I research the this question iOS app doesn't ask for location permission , I already have

NSLocationAlwaysUsageDescription
and
NSLocationWhenInUseUsageDescription


@IBOutlet weak var ownMapView: MKMapView!

let locationManager : CLLocationManager = CLLocationManager();


override func viewDidLoad() {
super.viewDidLoad();

self.locationManager.delegate = self;
self.locationManager.requestWhenInUseAuthorization();
self.locationManager.startUpdatingLocation();
}

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
guard status == .AuthorizedWhenInUse else
{
print("Location not using");
return;
}

print("Location using.");
ownMapView.showsUserLocation = true;
}


Even I added
NSLocationAlwaysUsageDescription
and
NSLocationWhenInUseUsageDescription
this is not working for me . It prints only "Location not using"

How do I request correctly ?

Answer

To understand this correctly check the CLLAuthorizationStatus doc: https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/#//apple_ref/c/tdef/CLAuthorizationStatus

CLAuthorizationStatus has several possible values:

  • NotDetermined - User has not yet made a decision to allow/deny to use location
  • Restricted - App is restricted to use location
  • Denied - User has denied to use location.
  • AuthorizedAlways - This app is authorized to start location services at any time.
  • AuthorizedWhenInUse - App is authorized to start most location services while running in the foreground

You are checking only "AuthorizedWhenInUse" status but you launch first its status is NotDetermined.

You can further check the status like below:

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

        if status  == .NotDetermined
        {
            print ("Loction use not determined")
            return
        }
        if status  == .Denied
        {
            print ("Location determined")
            return
        }
        guard status == .AuthorizedWhenInUse else
        {
            print("Location not using");
            return;
        }

        print("Location using.");
        ownMapView.showsUserLocation = true;
    }