I am writing an app that displays's a user's latitude, longitude, altitude, speed, course, and more. Everything displays right except for the user's speed. This is my code:
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: ""))
}
}
}
}
}
When I run the app the line with "self.speedLabel.text = String(location.speed)" gives me a bad instruction error with "fatal error: unexpectedly found nil while unwrapping an Optional value". I don't understand why the location.speed is not giving me a value. Then I tried:
if let speed = location.speed {
self.speedLabel.text = String(speed)
}
But then Xcode tells me I can not use an if let statement without an optional value. The thing is, the error that I got without the if let told me location.speed is an optional, so why can't I use it in an if let. Can anyone please tell me what is wrong with my code or possibly what I could be doing wrong. Thank you.