didUpdateLocations每当viewWillAppear调用重要位置时调用

问题描述:

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

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

为什么如果你只需要重要的位置更新,你有'self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation'?您是否在地图视图中显示用户位置? – Paulw11

+0

@ Paulw11 - 是的,我在MapView中显示用户位置 – Cintu

+0

这将导致地图请求用户位置更新,该位置更新正在传递给您的委托。您可以保留先前位置的记录,并检查位置更新中的距离;只有在距离大于某个阈值时更新服务器 – Paulw11

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

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 
    } 
}