我正在编写一个应用程序,显示用户的纬度,经度,高度,速度,航线等。除用户的速度外,一切都显示正常。这是我的代码:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var courseLabel: UILabel!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var altitudeLabel: UILabel!
@IBOutlet weak var adressLabel: UILabel!
var manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
self.latitudeLabel.text = String(location.coordinate.latitude)
self.longitudeLabel.text = String(location.coordinate.longitude)
self.courseLabel.text = String(location.course)
self.speedLabel.text = String(location.speed)
self.altitudeLabel.text = String(location.altitude)
CLGeocoder().reverseGeocodeLocation(location) { (placemarks, error) in
if error != nil {
print(error)
} else {
if let placemark = placemarks?[0] {
var adress = ""
if placemark.subThoroughfare != nil {
adress += placemark.subThoroughfare! + " "
}
if placemark.thoroughfare != nil {
adress += placemark.thoroughfare! + "\n"
}
if placemark.subLocality != nil {
adress += placemark.subLocality! + "\n"
}
if placemark.postalCode != nil {
adress += placemark.postalCode! + "\n"
}
if placemark.subAdministrativeArea != nil {
adress += placemark.subAdministrativeArea! + "\n"
}
if placemark.country != nil {
adress += placemark.country! + "\n"
}
self.adressLabel.text = adress.replacingOccurrences(of: "I-280 N", with: "")
print(adress.replacingOccurrences(of: "I-280 N", with: ""))
}
}
}
}
}
当我运行应用程序时,使用" self.speedLabel.text = String(location.speed)"给我一个错误的指令错误"致命错误:在解开一个Optional值时意外发现nil"。我不明白为什么location.speed没有给我一个价值。然后我试了一下:
if let speed = location.speed {
self.speedLabel.text = String(speed)
}
然后Xcode告诉我,如果没有可选值,我就不能使用if let语句。问题是,我得到的错误如果没有让我告诉我location.speed是可选的,那么为什么我不能在if中使用它。任何人都可以告诉我我的代码有什么问题,或者我可能做错了什么。谢谢。