So I am dealing with an issue where the LocationManager
file that I have, and the didUpdateLocations
function, is being called multiple times on application startup and I can't figure out what is causing it.
So I have the following LocationManager
:
import Foundation
import CoreLocation
import MapKit
final class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
@Published var userLocation: CLLocation?
@Published var defaultRegion: MKCoordinateRegion?
@objc static let getInstance = LocationManager()
private let locationManager = CLLocationManager()
override init() {
super.init()
locationManager.delegate = self
log.info("\n : (LocationManager) - Initialize Location Services inside init()")
}
func startUpdatingLocation() {
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func requestLocation() {
locationManager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
DispatchQueue.main.async {
self.userLocation = location
log.info("\n : (LocationManager) - Setup new location as: \(location)")
self.defaultRegion = MKCoordinateRegion(center: location.coordinate, span: USER_LOCATION_SPAN)
log.info("\n : (LocationManager) - Setup default region as \(location.coordinate.latitude) and \(location.coordinate.longitude).")
self.locationManager.stopUpdatingLocation()
log.info("\n : (LocationManager) - Stop updating the location.")
}
}
}
Then I am utilizing it in two separate view files called MapUIView
and MapUIView2
and I have the following object in both:
@ObservedObject var locationManager = LocationManager.getInstance
This causes the DispatchQueue.main.async
inside didUpdateLocations
to run through twice on application start - Is this normal behavior or is it possible to have the didUpdateLocations
to run just once, but handle multiple views?