Swift ios9: attempt to start updating MapKit location without requesting location authorization

I am writing a simple example for mapView suing swift, but I get print Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

I am adding a mapView to view the Controller and start placing it. I also call requestWhenInUseAuthorization()upstartUpdatingLocation()

I installed Info.plist

enter image description here

Now I install both NSLocationAlwaysUsageDescription, and NSLocationWhenInUseUsageDescriptionit does not work. enter image description here

Tere is my code, what's wrong?

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    var locationManager: CLLocationManager?
    var mapView: MKMapView?

    override func viewDidLoad() {
        super.viewDidLoad()

        let locationManager = CLLocationManager()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 10
        locationManager.delegate = self
        locationManager.pausesLocationUpdatesAutomatically = true

        if CLLocationManager.locationServicesEnabled() {

            let status: CLAuthorizationStatus = CLLocationManager.authorizationStatus()
            if status == CLAuthorizationStatus.NotDetermined {

                if #available(iOS 8.0, *) {
                    locationManager.requestWhenInUseAuthorization()
                } 
            }

            locationManager.startUpdatingLocation()

            self.locationManager = locationManager

        } else {

            print("locationServices disenabled")
        }

        let mapview = MKMapView(frame: self.view.bounds)
        mapview.mapType = .Standard
        mapview.showsUserLocation = true
        mapview.delegate = self
        self.mapView = mapview
        self.view.addSubview(mapview)

    }   
}
+4
source share
2 answers

As a warning, you are missing one of the two required lines in your plist

 NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription 
+6
source

This could be a problem:

let locationManager = CLLocationManager()

you put let and you already declared as a variable:

var locationManager: CLLocationManager?

"let"

0

Source: https://habr.com/ru/post/1618059/


All Articles