我正在创建一个以经度,纬度,海拔和速度出现的应用。
每当我运行应用程序时: 1.标签中没有显示位置数据2.我收到此错误消息:
fatal error: unexpectedly found nil while unwrapping an Optional value
我做错了什么?谢谢!
@IBOutlet weak var longitude: UILabel!
@IBOutlet weak var latitude: UILabel!
@IBOutlet weak var altitude: UILabel!
@IBOutlet weak var speed: UILabel!
var locationManager: CLLocationManager = CLLocationManager()
var startLocation: CLLocation!
@IBAction func reset(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)
altitude.text = String(format: "%.4f",
latestLocation.altitude)
if startLocation == nil {
startLocation = latestLocation as! CLLocation
}
var distanceBetween: CLLocationDistance =
latestLocation.distanceFromLocation(startLocation)
}
func locationManager(manager: CLLocationManager!,
didFailWithError error: NSError!) {
}
则...
override func viewDidLoad() {
super.viewDidLoad()
// Location
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
startLocation = nil
// Do any additional setup after loading the view, typically from a nib.
}
答案 0 :(得分:0)
将startLocation
作为一个隐式解包的可选项进行清理在这里是非常危险的,因为它并非总是如此!= nil。
尝试将其定义为可选项:
var startLocation: CLLocation?
并相应地更改代码的resto,并在需要时进行适当的检查。
例如,当您计算距离时:
if let startLocation = startLocation {
var distanceBetween: CLLocationDistance =
latestLocation.distanceFromLocation(startLocation)
}
也许您的代码中的其他位置startLocation
可能nil
由于尝试设置纬度标签文本时会出现nil异常,因此我首先会检查是否通过Interface Builder正确连接了该标签。它的声明左边的小子弹是彩色的吗?无论如何,您可以在该行代码之前放置一个断点,而不是检查什么是零而不应该。