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

时间:2015-12-01 05:11:06

标签: ios swift mkmapview ios9 cllocation

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

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

之前致电startUpdatingLocation()

我设置了Info.plist

enter image description here

现在我同时设置NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription,但它不起作用。 enter image description here

Tere是我的代码,出了什么问题?

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)

    }   
}

2 个答案:

答案 0 :(得分:6)

警告告诉你遗漏了两条必需的弦乐中的一条

 NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription 

答案 1 :(得分:0)

这可能是问题所在:

let locationManager = CLLocationManager()

你放了let,你已经宣布像变量:

var locationManager: CLLocationManager?

在没有“让”的情况下使用它