我在同一UIViewController
中使用CLLocationManager
和MKMapView
。 我只想在重要位置更改时才调用 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
}
您可以保存最后的位置并检查didUpdateLocations
方法内部,如果不同,请采取适当的操作。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location : CLLocation = locations.last!
if location.coordinate.latitude != lastLat && location.coordinate.longitude != lastLon{
// take action
}
}