减少位置管理器更新的频率

问题描述 投票:-1回答:1

有没有办法减少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个回答
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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.