我对斯威夫特非常陌生,我无法理解以下代码:
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"
}
}
}我不明白为什么这段代码没有启动。尽管它没有出现任何错误,但viewDidLoad()似乎从未被调用过,因此该类不会对我的应用程序的其余部分做任何事情。请帮我找到正确的初始化器。
发布于 2022-05-23 19:10:00
正如我在注释中所说的,而不是UIViewController将类声明为NSObject的子类,并在标准的init方法中初始化位置管理器。
框架从未调用过updateLocationInfo。您必须实现locationManager(_ didUpdateLocations:)并从位置获取速度。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let speed = locations.first?.speed else { return }
let speedToKPH = speed * 3.6
if speedToKPH > 0 {
speedtest = String(format: "%.0f km/h", speedToKPH)
} else {
speedtest = "0 km/h"
}
}发布于 2022-05-23 19:48:03
我的完整代码现在如下所示:
import Foundation
import MapKit
import CoreLocation
class SpeedViewModel: NSObject, ObservableObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
var lastLocation: CLLocation!
var speedtest = " km/h"
override init() {
super.init()
// 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()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let speed = locations.first?.speed else { return }
let speedToKPH = speed * 3.6
if speedToKPH > 0 {
speedtest = String(format: "%.0f km/h", speedToKPH)
} else {
speedtest = "0 km/h"
}
}
}做它应该做的事。谢谢你@vadian
https://stackoverflow.com/questions/72352721
复制相似问题