位置许可检查和授权

Ste*_*eve 7 permissions location mapkit ios swift

我希望我的程序在地图上显示用户位置.它起初工作然后随机停止所以我添加下面的代码试图解决它但我遇到了问题.提前致谢!

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if CLLocationManager.locationServicesEnabled()
        {

            let status: CLAuthorizationStatus = CLLocationManager.authorizationStatus()
            if status == CLAuthorizationStatus.NotDetermined
            {
                locationManager.requestAlwaysAuthorization()
            }
            } else {

                print("locationServices disenabled")
            }
            locationManager.startUpdatingLocation()
            self.locationManager.startUpdatingLocation()
            self.mapView.showsUserLocation = true
            mapView.delegate = self
            centerMapOnLocation(initialLocation)
            addBoundry()
    }
Run Code Online (Sandbox Code Playgroud)

Lio*_*ion 14

你需要打电话,

locationManager.requestAlwaysAuthorization() 
Run Code Online (Sandbox Code Playgroud)

同样

 locationManager.requestWhenInUseAuthorization()
Run Code Online (Sandbox Code Playgroud)

在前台也能顺利使用位置!!!

你不应该需要两个实例来调用startupdatinglocation.留一个.您应该使用实例或全局变量而不是本地来获取整个范围内的位置.

更新:

您必须设置两个键info.plist,NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription使用它的用法说明.


小智 5

NSLocationAlwaysUsageDescription即使在 info.plist 中设置并设置,我也遇到了同样的问题NSLocationWhenInUseUsageDescription。我的调试器告诉我也要设置NSLocationAlwaysAndWhenInUseUsageDescription...所以我就这么做了。有效!


小智 5

如果您想要“WhenInUse”通知,您应该只在 info.plist 中添加“隐私 - 使用时位置使用说明”,但如果您想要“始终”访问,您的 info.plist 应该类似于此 info.plist 屏幕截图:

图像

您不必添加任何请求授权,例如 requestAlwaysAuthorization 或 requestWhenInUseAuthorization