【发布时间】:2017-08-09 07:02:13
【问题描述】:
我在同一个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 正在被调用。
【问题讨论】:
-
如果您只想更新重要的位置信息,为什么还要使用
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation?您是否在地图视图上显示用户位置? -
@Paulw11 - 是的,我在 MapView 中显示用户位置
-
这将导致地图请求用户位置更新,该更新将传送给您的代表。您可以记录您之前的位置,并在位置更新中查看距离;仅当距离大于某个阈值时才更新服务器
标签: ios swift mkmapview cllocationmanager