I am pretty new to swift and can't get my head around the following code:
import Foundation
import MapKit
import CoreLocation
class SpeedViewModel: UIViewController, ObservableObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
var speedtest = " km/h"
override func viewDidLoad() {
super.viewDidLoad()
print ("test1111")
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.startUpdatingLocation()
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateLocationInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees, speed: CLLocationSpeed, direction: CLLocationDirection) {
let speedToKPH = (speed * 3.6)
if (speedToKPH > 0) {
speedtest = (String(format: "%.0f km/h", speedToKPH))
} else {
speedtest = "0 km/h"
}
}
}
I don't understand why this code is not starting. Although it is not having any errors, it seems like the viewDidLoad() is never called and therefore the class is not doing anything to the rest of my app. Please help me to find the right initializer.
As I said in the comments, rather than
UIViewControllerdeclare the class as a subclass ofNSObjectand initialize the location manager in the standardinitmethod.updateLocationInfois never being called by the framework. You have to implementlocationManager(_ didUpdateLocations:)and get the speed from the location.