swift ios9:尝试在不提示位置授权的情况下启动 MapKit 位置更新

swift ios9: Trying to start MapKit location updates without prompting for location authorization

我为 mapView 写了一个简单的示例 swift,但我得到了打印 Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

我将 mapView 添加到 viewController 并开始定位。我也在 startUpdatingLocation()

之前调用 requestWhenInUseAuthorization()

我设置了Info.plist

现在我同时设置了 NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription ,它不起作用。

这是我的代码,怎么了?

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)

    }   
}

因为警告告诉您 plist 中缺少两个必需的字符串之一

 NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription 

这可能是问题所在:

let locationManager = CLLocationManager()

你放了 let 并且你已经像变量一样声明了:

var locationManager: CLLocationManager?

不使用 "let"