【问题标题】:didUpdateLocations called every time when viewWillAppear for Significant Location Change每次 viewWillAppear 发生重大位置变化时调用 didUpdateLocations
【发布时间】:2017-08-09 07:02:13
【问题描述】:

我在同一个UIViewController 中使用CLLocationManagerMKMapView。 我只想在位置发生重大变化时调用 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 时才调用它。

我发现它是因为MKMapViewdidUpdateLocations 正在被调用。

【问题讨论】:

  • 如果您只想更新重要的位置信息,为什么还要使用self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation?您是否在地图视图上显示用户位置?
  • @Paulw11 - 是的,我在 MapView 中显示用户位置
  • 这将导致地图请求用户位置更新,该更新将传送给您的代表。您可以记录您之前的位置,并在位置更新中查看距离;仅当距离大于某个阈值时才更新服务器

标签: ios swift mkmapview cllocationmanager


【解决方案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
}

【讨论】:

    【解决方案2】:

    您可以保存最后的位置并在didUpdateLocations 方法中检查,如果不同,请采取适当的措施。

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
        let location : CLLocation = locations.last!
    
        if location.coordinate.latitude != lastLat && location.coordinate.longitude != lastLon{
            // take action
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      相关资源
      最近更新 更多