我在同一个CLLocationManager
中使用MKMapView
和UIViewController
。
我想只在重要位置发生变化时调用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
。
答案 0 :(得分:1)
您可以手动检查上次保存位置的距离。试试这个。
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
}
答案 1 :(得分:0)
您可以保存最后的位置并检查char
方法内部,如果不相同则采取相应措施。
didUpdateLocations