获取有关请求位置权限的错误

Getting error about asking for location permission

获取有关请求位置权限的错误:"Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first."问题是我已经这样做了,之前它工作正常,直到我为完全不同的东西添加了 url 方案。

这是我的 ViewController:

override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestAlwaysAuthorization()
        self.locationManager.startUpdatingLocation()
        self.mapView.showsUserLocation = true
        //your loc
        mapView.delegate = self
        let initialLocation = CLLocation(latitude: 39, longitude: 77)
        centerMapOnLocation(initialLocation)
        }

您需要询问用户是否已授予跟踪其位置的权限:

if CLLocationManager.authorizationStatus() == .NotDetermined {
    manager.requestAlwaysAuthorization()
}

那么你需要一个回调函数,当权限被授予时会被调用:

func locationManager(manager: CLLocationManager,
                     didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
    if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
        manager.startUpdatingLocation()
        // ...
    }
}

记住你必须异步执行此操作,因为你知道何时请求权限(例如,当视图控制器加载时),但你不知道用户何时单击允许按钮。

并且不要忘记设置NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription,否则不会提示。