当我在iphone上运行我的Swift应用程序时,为什么CLLocationmanager不要求gps权限?

时间:2016-02-28 20:35:46

标签: ios swift cllocationmanager

我使用以下代码构建了一个快速演示应用程序:https://stackoverflow.com/a/35685278/3766930

我使用的代码是:

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet var mapView: MKMapView!
    var locationManager: CLLocationManager?

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()
        locationManager!.delegate = self

        if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            locationManager!.startUpdatingLocation()
        } else {
            locationManager!.requestWhenInUseAuthorization()
        }
    }

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


        switch status {
        case .NotDetermined:
            print("NotDetermined")
        case .Restricted:
            print("Restricted")
        case .Denied:
            print("Denied")
        case .AuthorizedAlways:
            print("AuthorizedAlways")
        case .AuthorizedWhenInUse:
            print("AuthorizedWhenInUse")
            locationManager!.startUpdatingLocation()
        }
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let location = locations.first!
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500)
        mapView.setRegion(coordinateRegion, animated: true)
        locationManager?.stopUpdatingLocation()
        locationManager = nil
    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Failed to initialize GPS: ", error.description)
    }
}

我还添加了对plist文件的权限:

NSLocationWhenInUseUsageDescription

但是当我在手机上部署应用程序并运行它时 - 它没有问我任何权限,而且在日志文件中我只得到了:

NotDetermined

如何强制我的应用在用户启动时始终使用gps坐标?我想在应用程序的最开始介绍检查GPS是否已启用,如果没有 - 请避免运行应用程序,只是提示用户打开GPS数据。这在Swift中是否可行并且可以实现?

2 个答案:

答案 0 :(得分:1)

什么是AuthorizedAlways

由于您要求使用时权限,因此您的info.plist需要具有NSLocationWhenInUseUsageDescription的字符串值

答案 1 :(得分:0)

iOS上,您无法选择明确选择GPS收音机,但您可以选择打开收音机所需的精确度。

locationManager!.desiredAccuracy = kCLLocationAccuracyBestForNavigation

这将使用 GPS 启动您的CLLocationManager

考虑到GPS需要几秒钟的时间才能为您提供最准确的位置,因此您可以过滤掉locationManager:didUpdateLocations:方法中任何高于20.0的位置或您认为过于透彻的任何值