【问题标题】:Reduce how often location manager updates减少位置管理器更新的频率
【发布时间】:2019-03-15 19:06:21
【问题描述】:

有什么方法可以减少 locationManager 更新的次数?目前30秒内更新100多次!我的应用收集用户的坐标并将其推送到数据库,但我收集的坐标太多。

我可以减少应用更新用户位置的次数吗?

 func locationManager(_ manager: CLLocationManager, didUpdateLocations 

locations: [CLLocation]) {

            let lat = LocationManager.sharedInstance.location.coordinate.latitude
            let long = LocationManager.sharedInstance.location.coordinate.longitude
}

【问题讨论】:

标签: swift cllocationmanager locationmanager


【解决方案1】:

使用CLLocationManagerdistanceFilter 属性。

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
    // MARK: - Variables
    let locationManager = CLLocationManager()

    // MARK: - IBOutlets
    @IBOutlet weak var mapView: MKMapView!

    // MARK: - IBAction

    // MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        /* delegate */
        mapView.delegate = self
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        /* checking location authorization */
        checkLocationAuthorizationStatus()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.startUpdatingLocation()
            locationManager.allowsBackgroundLocationUpdates = true
            locationManager.pausesLocationUpdatesAutomatically = false
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.distanceFilter = 20.0 // 20.0 meters
        }
    }

    // MARK: - Authorization
    func checkLocationAuthorizationStatus() {
        if CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways {

        } else {
            locationManager.requestWhenInUseAuthorization()
        }
    }

    // MARK: - CLLocationManager delegate methods
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let mostRecentLocation = locations.last else {
            return
        }

        print(mostRecentLocation)
    }
}

【讨论】:

    猜你喜欢
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    相关资源
    最近更新 更多