每当viewWillAppear显示重要位置更改时,都会调用didUpdateLocations

时间:2017-08-09 07:02:13

标签: ios swift mkmapview cllocationmanager

我在同一个CLLocationManager中使用MKMapViewUIViewController。 我想只在重要位置发生变化时调用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

2 个答案:

答案 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