我正在尝试制作一个简单的应用程序来显示: 纬度 经度 水平精度 高度 垂直精度 起点位置
我的代码是:
@IBOutlet weak var latitude: UILabel!
@IBOutlet weak var longitude: UILabel!
@IBOutlet weak var horizontalAccuracy: UILabel!
@IBOutlet weak var altitude: UILabel!
@IBOutlet weak var verticalAccuracy: UILabel!
@IBOutlet weak var distance: UILabel!
var locationManager: CLLocationManager = CLLocationManager()
var startLocation: CLLocation!
@IBAction func resetDistance(sender: AnyObject) {
startLocation = nil
}
func locationManager(manager: CLLocationManager!,
didUpdateLocations locations: [AnyObject]!)
{
var latestLocation: AnyObject = locations[locations.count - 1]
latitude.text = String(format: "%.4f",
latestLocation.coordinate.latitude)
longitude.text = String(format: "%.4f",
latestLocation.coordinate.longitude)
horizontalAccuracy.text = String(format: "%.4f",
latestLocation.horizontalAccuracy)
altitude.text = String(format: "%.4f",
latestLocation.altitude)
verticalAccuracy.text = String(format: "%.4f",
latestLocation.verticalAccuracy)
if startLocation == nil {
startLocation = latestLocation as! CLLocation
}
var distanceBetween: CLLocationDistance =
latestLocation.distanceFromLocation(startLocation)
distance.text = String(format: "%.2f", distanceBetween)
}
func locationManager(manager: CLLocationManager!,
didFailWithError error: NSError!) {
}
然后在 ViewDidLoad 部分:
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
startLocation = nil
我一直收到错误:在 latitude.text 行上(一切都正确连接)
fatal error: unexpectedly found nil while unwrapping an Optional value
(数据库)
我将如何添加 if let 语句?你能帮我找出问题所在吗?
谢谢!
最佳答案
欢迎使用 swift 。您不能对 AnyObject 做任何事情。像这样放下:
let latestLocation = locations.last as! CLLocation
此外,您说“一切都正确连接”,但我不确定我是否相信;尝试执行 println(latitude)
以确保。
最后,这段代码是行不通的:
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
问题是授权请求是异步的。因此,您可能在实际获得授权之前就开始更新位置。在开始请求更新之前,您必须等到您真正拥有授权。
关于ios - 我的 CLLocation 做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30179968/