gpt4 book ai didi

ios - 我的 CLLocation 做错了什么?

转载 作者:搜寻专家 更新时间:2023-11-01 06:22:53 24 4
gpt4 key购买 nike

我正在尝试制作一个简单的应用程序来显示:纬度经度水平精度高度垂直精度起点位置

我的代码是:

@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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com