CLLocationManager 未确定位置

CLLocationManager not determining location

我在获取用户的当前位置时遇到了一些问题。我知道有很多关于这个主题的问题,但我已经阅读并完全按照 Apple 文档告诉我的去做,但仍然没有用。

我的 MasterViewController 中有以下代码:

class MasterViewController: UITableViewController, CLLocationManagerDelegate {

var detailViewController: DetailViewController? = nil

var locationManager:CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.navigationItem.leftBarButtonItem = self.editButtonItem()
    let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "printPlace:")
    self.navigationItem.rightBarButtonItem = addButton
    if let split = self.splitViewController {
        let controllers = split.viewControllers
        self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
    }

    if !CLLocationManager.locationServicesEnabled() {
        println("location services disabled")
    }
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
}


func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
    println("found location")
}

@IBAction func printPlace(sender: AnyObject) {
    let currentLocation: CLLocationCoordinate2D = locationManager.location.coordinate
    println("\(currentLocation.latitude) , \(currentLocation.longitude)")
}

我还在 info.plist 中添加了 NSLocationWhenInUseUsageDescription 键。但是,当我 运行 这段代码时, didUpdateLocations 从未被调用,并且 printPlace 给出了一个致命错误,因为 locationManager.location 为零。谁能看出我在这里做错了什么?

啊,问题可能是你说你为 NSLocationWhenInUseUsageDescription 更新了你的 .plist 但在你的代码中你调用了 locationManager.requestAlwaysAuthorization() 这是不同的东西。您需要将正确的添加到 .plist (NSLocationAlwaysUsageDescription),或者仅在使用时请求,如下所示:locationManager.requestWhenInUseAuthorization()

此外,正如您对原始 post 的评论指出的那样,它应该是 NSLocationWhenInUseUsageDescription,而不是 NSLocationWhenInUsageDescription