CoreLocation requestWhenInUseAuthorization()在Swift中不起作用

时间:2015-07-27 22:32:54

标签: ios swift cocoa-touch core-location

我希望我的应用显示用户的位置,但不要求使用WhenInUseAuthorization。我在Info.plist中添加了NSLocationWhenInUseUsageDescription键。我在iOS模拟器中尝试了模拟位置和放大器在一个实际的设备上。

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!

    var locationManager = CLLocationManager()

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

        if CLLocationManager.authorizationStatus() == .NotDetermined {
            self.locationManager.requestWhenInUseAuthorization()
        }
    }

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

        if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            locationManager.startUpdatingLocation()
            mapView.showsUserLocation = true

            let userLocation = CLLocationCoordinate2DMake(locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude)
            mapView.region = MKCoordinateRegionMakeWithDistance(userLocation, 100, 100)

        } else {

            let defaultLocation = CLLocationCoordinate2DMake(45.5017, -73.5673)
            mapView.region = MKCoordinateRegionMakeWithDistance(defaultLocation, 100, 100)
        }
    }
}

3 个答案:

答案 0 :(得分:1)

这是我的错误,我在测试文件夹的Info.plist中添加了NSLocationWhenInUseUsageDescription键,而不是主项目的plist。

答案 1 :(得分:0)

您是否在模拟器上更改了用户位置?如果您没有更改它,则无法获得“用户位置”。

答案 2 :(得分:0)

也许你过早地调用requestWhenInUseAuthorization。尝试拨打didChangeAuthorizationStatus代表。

func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    if status == CLAuthorizationStatus.NotDetermined {
        locationManager.requestWhenInUseAuthorization()
    }
}