【发布时间】: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