ios - 我的 CLLocation 做错了什么?

标签 ios iphone swift

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

我的代码是:

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

相关文章:

iphone - 如何使用 iOS5 将 Twitter 帐户关注者访问到 iPhone?

ios - i18n 与 Cocoapods 和动态库

ios - 如何在我的应用程序中使用 Facebook 登录并在成功登录后移至下一个页面/ View Controller ?

javascript - TypeError: Undefined 不是一个函数。 iOS Safari 评估功能。 CoffeeScript

iphone - 移动棒图、 anchor 、动画或其他东西......?

ios - 按下按钮时如何显示事件卡

iphone - 旋转后获取 UIViewController View 的大小

ios - 滚动到 CollectionView 中的上一张/下一张图像时,正确计算颜色不透明度偏移以更改背景颜色?

ios - 具有不同格式的 Swift Date 对象

ios - 如果对象无效,如何检查 Swift?