【问题标题】:CLLocationManager not determining locationCLLocationManager 未确定位置
【发布时间】:2015-10-22 00:26:22
【问题描述】:

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

【问题讨论】:

  • 您是在设备上还是在模拟器中尝试这个?
  • 在运行 iOS 8 的 iPhone 5 设备上
  • 应用程序是否要求您允许使用您的位置?您可能必须删除该应用并将其重新刷新到设备才能进行测试。
  • 你写的时候是用NSLocationWhenInUsageDescription还是NSLocationWhenInUseUsageDescription?我经常有这个错字而忘记了Use。一旦你改变它,它仍然不起作用,然后按照下面的答案
  • 对不起,错字只是在问题中。将编辑

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


【解决方案1】:

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

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

【讨论】:

  • 是的,如果你没有匹配的对,它甚至不会给你一个错误,它不会做任何事情。
  • 就是这样!谢谢!
  • 没问题!很高兴我能帮上忙。
  • 另外,作为一个良好做法的说明,如果您在收到位置后使用 locationManager 完成,请务必停止它!
猜你喜欢
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
  • 2012-03-30
相关资源
最近更新 更多