gpt4 book ai didi

ios - didUpdateLocations 每次当 viewWillAppear 发生重大位置变化时调用

转载 作者:可可西里 更新时间:2023-11-01 02:02:03 25 4
gpt4 key购买 nike

我在同一个 UIViewController 中使用 CLLocationManagerMKMapView。我只想在重要位置发生变化时调用 API。

import UIKit
import CoreLocation
import MapKit


class ViewController: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!

var locationManager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationManager.requestAlwaysAuthorization()
self.locationManager.delegate = self
self.locationManager.startMonitoringSignificantLocationChanges()
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
self.locationManager.distanceFilter = 500
mapView.showsUserLocation = true
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locations \(locations)")
}

}

在此,主要问题是每当我调用应用程序背景和前景 didUpdateLocations 时。我希望仅在位置发生重大变化时调用它,而不是每次调用 viewWillAppear 时调用它。

我发现它是因为 MKMapView,正在调用 didUpdateLocations

最佳答案

您可以手动检查与上次保存位置的距离。试试这个。

var lastLocation: CLLocation?
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

if let lastLocation = lastLocation, let newLocation = locations.last {
if (lastLocation.distance(from: newLocation) < manager.distanceFilter) {
return
}
}

print("locations \(locations)")
lastLocation = locations.last
}

关于ios - didUpdateLocations 每次当 viewWillAppear 发生重大位置变化时调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45583716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com