只有在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的位置,看看这是否适用于您。

最新更新