CLLocationManager requestWhenInUseAuthorization()不起作用

时间:2015-02-22 19:03:50

标签: ios swift core-location cllocationmanager

我正在尝试在我的iOS应用中使用位置服务,但出于某种原因,requestWhenInUseAuthorization无效。当用户第一次使用该应用程序时,提示按正常方式询问权限,但是当您第二次打开应用程序时,由于某种原因didChangeAuthorizationStatus方法未被调用,因此我无法显示用户当前位置地图。

我的代码如下:

 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    var config:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    config.URLCache = NSURLCache(memoryCapacity: 2 * 1024 * 1024, diskCapacity: 10 * 1024 * 1024, diskPath: "MarkerData")
    markerSession = NSURLSession(configuration: config)
 }



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

        locationManager.startUpdatingLocation()
        mapView.delegate = self
        mapView.myLocationEnabled = true
        mapView.settings.myLocationButton = true
     }
 }

1 个答案:

答案 0 :(得分:11)

首先,您需要在info.plist文件中添加NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription(如果您想在后台使用)。见下图:

enter image description here

接下来,在您的swift文件中,您需要在locationManager.requestWhenInUseAuthorization()方法中调用locationManager.requestAlwaysAuthorization()viewDidLoad()

最后,您可以在locationManager委托方法中执行mapView.camera = GMSCameraPosition(target: locations.last!.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

示例代码:

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager = CLLocationManager();

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        var camera = GMSCameraPosition.cameraWithLatitude(-33.86,
            longitude: 151.20, zoom: 6)
        var mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
        mapView.myLocationEnabled = true
        self.view = mapView

        locationManager.delegate = self
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if #available(iOS 8.0, *) {
            print("iOS >= 8.0.0")
            locationManager.requestAlwaysAuthorization()
        }
        locationManager.startUpdatingLocation()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        println(locations.last)

        var mapView = self.view as! GMSMapView

        mapView.camera = GMSCameraPosition(target: locations.last!.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
    }
}

您可以this post,了解有关iOS 8中LocationManager更改的更多详细信息。