我正在尝试创建一个简单的应用程序,显示: 纬度 经度 水平精度 高度 垂直精度 位置从开始
我的代码是:
@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
(lldb)
我如何添加 if 语句?你能帮我找到问题吗?
谢谢!
答案 0 :(得分:2)
欢迎来到Swift。你不能用AnyObject做任何事情。像这样抛弃:
let latestLocation = locations.last as! CLLocation
另外,你说"一切都正确连接了#34;但是我不确定我是否相信;尝试println(latitude)
来确保。
最后,这段代码不起作用:
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
问题是授权请求是异步。因此,您可能在实际获得授权之前开始更新位置。在开始要求更新之前,您必须等到实际拥有授权。
答案 1 :(得分:2)
关于如何获取授权:
首先将 NSLocationWhenInUseUsageDescription 添加到info.plist文件中
然后在viewDidload中:
if NSString(string:UIDevice.currentDevice().systemVersion).doubleValue > 8 {
locationManager.requestWhenInUseAuthorization()
}
然后是这个委托方法,启动updateingLoation
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status != CLAuthorizationStatus.Denied{
locationManager.startUpdatingLocation()
}
}
然后,当您获得位置时,可以将其转换为CLLocation
matt 帖子
您也可以参考此链接了解详细信息,这是我之前回答的答案 Swift: Exception while trying to print CLLocationSpeed "unexpectedly found nil while unwrapping an Optional value"