user10460877
user10460877

Reputation:

Reduce how often location manager updates

Is there any way to reduce the number of times the locationManager updates? Currently is updated over 100 times in 30 seconds! My app collects the coordinates of the user and pushes this to a database, But I'm collecting too many coordinates.

Can I reduce the number of times the app updates user location?

 func locationManager(_ manager: CLLocationManager, didUpdateLocations 

locations: [CLLocation]) {

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

Upvotes: 0

Views: 1538

Answers (1)

El Tomato
El Tomato

Reputation: 6707

Use CLLocationManager's distanceFilter property.

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)
    }
}

Upvotes: 3

Related Questions