CLLocationManager无法确定位置

时间:2015-07-30 14:59:19

标签: ios swift cocoa-touch core-location cllocationmanager

我在获取用户当前位置时遇到了一些麻烦。我意识到关于这个主题有很多问题,但是我已经阅读了它们并完全按照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 为nil。谁能看到我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

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

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