Swift中基于CoreLocation实现实时距离测量的启停控制(兼容速度测量)
问题根因
之前试图通过返回值从CLLocationManager代理回调中传出location变量的思路,完全不适配Core Location的异步运行机制:
didUpdateLocations是系统在获取到有效定位后异步触发的回调,和调用定位相关方法的代码执行栈完全隔离- 硬要在这个代理方法中通过返回值传值,不仅无法拿到实时更新的定位结果,还可能打断代理方法的正常执行流程,直接导致已经实现的速度显示功能失效
正确实现思路
距离测量不需要从代理方法向外传值,直接在类的成员变量中维护测量状态、累计距离、上一次有效定位点即可,完全复用现有「开始/停止」按钮的交互框架:
- 点击开始时:重置累计距离、清空上一次有效定位点,再开启定位更新与计时
- 每次代理拿到新的有效定位时:先计算当前定位与上一个有效定位的位移值,累加到总距离上,同时保留原有速度显示逻辑
- 点击停止时:关闭定位更新,清空临时测量状态即可
需补充的类属性
// 累计测量的总距离,单位米 private var totalDistance: CLLocationDistance = 0 // 上一次参与位移计算的有效定位点 private var lastValidLocation: CLLocation?
修改后的核心代码
@IBAction func startStopButtonDidTouch(_ sender: UIButton) { if isStarted { // 点击停止 timer?.invalidate() isStarted = false locationManager.stopUpdatingLocation() // 停止时清理临时测量状态 lastValidLocation = nil startStopButton.setTitle("START", for: .normal) } else { // 点击开始 // 重置测量数据与界面显示 totalDistance = 0 lastValidLocation = nil distanceLabel.text = "0" // 开启定位与计时 locationManager.startUpdatingLocation() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimeLabel), userInfo: nil, repeats: true) isStarted = true startStopButton.setTitle("STOP", for: .normal) } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let currentLocation = locations.last else { return } // 过滤精度不达标的定位点,避免GPS漂移导致距离虚高 guard currentLocation.horizontalAccuracy > 0, currentLocation.horizontalAccuracy < 30 else { return } // 原有速度显示逻辑保持不变 speedLabel.text = "\(Int(currentLocation.speed * 3.6))" // 距离累计计算 if let previousLocation = lastValidLocation { let displacement = currentLocation.distance(from: previousLocation) totalDistance += displacement // 更新距离显示,按需转换单位(此处按公里展示) distanceLabel.text = String(format: "%.1f", totalDistance / 1000) } // 更新上一次有效定位点,供下一次位移计算使用 lastValidLocation = currentLocation }
提示:定位精度的过滤阈值可以根据实际使用场景调整,进一步降低GPS漂移对测量结果的影响。
内容的提问来源于stack exchange,提问作者Мухаммед Аралбек
相关产品推荐
相关产品推荐

