我在同一UIViewController
中使用CLLocationManager
和MKMapView
。 我只想在重要位置發生變化時調用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
被調用。
爲什麼如果你只需要重要的位置更新,你有'self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation'?您是否在地圖視圖中顯示用戶位置? – Paulw11
@ Paulw11 - 是的,我在MapView中顯示用戶位置 – Cintu
這將導致地圖請求用戶位置更新,該位置更新正在傳遞給您的委託。您可以保留先前位置的記錄,並檢查位置更新中的距離;只有在距離大於某個閾值時更新服務器 – Paulw11