Swift 2 - 无法使用CLLocationManager获取用户位置

时间:2015-09-26 20:58:36

标签: ios swift swift2 xcode7 cllocationmanager

这是我的VC代码:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        mapView.showsUserLocation = true
    }

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        mapView.showsUserLocation = (status == .AuthorizedAlways)
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
}

我还在plist文件中添加了NSLocationWhenInUseUsageDescription。我有CoreLocationMapKit框架,知道为什么这不起作用?它不会在地图上显示用户位置,也不会打印出用户的坐标。在堆栈溢出时没有在网上找到任何东西。

3 个答案:

答案 0 :(得分:5)

这对我有用

Swift 2 - (Xcode 7.2.1)

<强> ViewController.swift


import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager: CLLocationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

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

        self.locationManager.stopUpdatingLocation()

        let latestLocation = locations.last

        let latitude = String(format: "%.4f", latestLocation!.coordinate.latitude)
        let longitude = String(format: "%.4f", latestLocation!.coordinate.longitude)

        print("Latitude: \(latitude)")
        print("Longitude: \(longitude)")
    }
}

<强> info.plist中

添加新行

信息属性列表: NSLocationWhenInUseUsageDescription

输入:字符串

价值:应用程序使用此信息向您显示您的位置

答案 1 :(得分:0)

尝试通过方法locations中获取数组locationManager(_:,didUpdateLocations locations: [CLLocations])的最后一个对象来获取位置。

这样的事情:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = locations.last!
        print("locations = \(locValue.latitude) \(locValue.longitude)")
}  

答案 2 :(得分:0)

您必须在plist中使用这些位置访问权限。

  1. NSLocationAlwaysAndWhenInUseUsageDescription
  2. NSLocationWhenInUseUsesDescription

您不是一直使用并且处于InUse渗透状态

Apple注:

此应用已尝试访问没有使用说明的隐私敏感数据。应用程序的 Info.plist必须同时包含NSLocationAlwaysAndWhenInInUseUsageDescription和NSLocationWhenInUseUsageDescription 键,并带有字符串值,向用户说明应用程序如何使用此数据