仅在 Swift 中点击按钮后更新速度

Updating speed only after button tapped in Swift

我正在制作一个实时测量速度和距离的应用程序。所以之前那个应用程序在点击按钮时开始更新位置。但是这种方法在点击按钮后需要时间。如果我将 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"
}

我不确定这是最好的解决方案,但您可以使用一个额外的变量来确保当您在应用程序启动时获取位置时,不应进行速度和距离计算。像这样:

let locationManager = CLLocationManager()
   override func viewDidLoad() {
         super.viewDidLoad()

        isToPerformCalculations = false
        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
        isToPerformCalculations = true
        startStopButton.setTitle("STOP", for: .normal)
    }
  }
    
    func locationManager (_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])   {
    let location = locations[0]
    locationManager.stopUpdatingLocation()
    if isToPerformCalculations {
        if (startLocation == nil) {
           startLocation = location;
        }
        let endLocation = location;

    
         speedLabel.text = "\(Int(location.speed * 3.6))"
         let distance = startLocation.distance(from: endLocation) / 1000 //m->km
         distanceLabel.text = "\(String(format: "%.1f", distance)) km"
    }
}

我也改变了你的地方 stopUpdatingLocation,看看这是否适合你。