有没有办法减少locationManager更新的次数?目前在30秒内更新超过100次!我的应用程序收集用户的坐标并将其推送到数据库,但我收集的坐标太多了。
我可以减少应用更新用户位置的次数吗?
func locationManager(_ manager: CLLocationManager, didUpdateLocations
locations: [CLLocation]) {
let lat = LocationManager.sharedInstance.location.coordinate.latitude
let long = LocationManager.sharedInstance.location.coordinate.longitude
}
使用CLLocationManager
的distanceFilter
财产。
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)
}
}