【发布时间】:2020-11-24 10:19:46
【问题描述】:
我正在制作一个实时测量速度和距离的应用。所以之前该应用程序在点击按钮时开始更新位置。但是这种方法在点击按钮后需要一些时间。如果我将 locationManager.startUpdatingLocation 放在 viewDidLoad 中,速度和距离会立即开始测量,而无需点击开始按钮。只有在点击开始按钮时,我才能立即开始测量速度和距离?这是我的代码。
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
@IBAction func startStopButtonDidTouch(_ sender: UIButton) {
if isStarted { //When tapped STOP
locationManager.stopUpdatingLocation()
startStopButton.setTitle("START", for: .normal)
} else { //When tapped START
startStopButton.setTitle("STOP", for: .normal)
}
}
func locationManager (_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
speedLabel.text = "\(Int(location.speed * 3.6))"
if (startLocation == nil) {
startLocation = location;
}
let endLocation = location;
let distance = startLocation.distance(from: endLocation) / 1000 //m->km
distanceLabel.text = "\(String(format: "%.1f", distance)) km"
}
【问题讨论】:
-
我不确定我是否理解你,但你为什么不直接
startUpdatingLocation处理开始按钮的点击? -
如果我这样做,需要一些时间才能获得位置。当用户打开它时,应用程序应该立即获取位置。但在屏幕中,速度和距离应该等于 0,直到用户点击开始按钮。
-
更新位置,。和记录速度是两个不同的东西 - 正如@kyers 建议的那样,应用程序打开后立即开始更新位置,但使用按钮设置标志,并且在 didUpdateLocations 中,仅在设置标志时更新速度
-
检查我的答案,然后尝试一下。它可能需要一些调整,但这个想法应该可行。
-
第一次点击开始按钮时一切正常。但是在点击重置后,重新开始速度和距离不起作用。看起来你错过了 var isToCalc.... = False in viewController。我还尝试添加 isToPerformCalculations = false 来重置和停止功能,但它不起作用
标签: ios swift performance distance cllocation