LocationManager triggering didUpdateLocations twice instead of once for each location change

39 Views Asked by At

I am trying to capture and save the location using LocationManager but having trouble with it triggering didUpdateLocations twice for every location change. I need it to only do this once as it's filling up my data model with duplicates for every reading.

The following is triggering twice and saving twice for each change it detects:

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        /// Too slow, not driving
        guard let speed = locations.last?.speed, speed > AppDefaults.gps.drivingSpeedThreshold else {
            return
        }
        ///  We are driving so do stuff
        if let currentLocation = locations.last {
            locationUpdateCounter = locationUpdateCounter + 1
            if locationUpdateCounter >= 5 {
                updateRegion(currentLocation)
                saveLocation(location: currentLocation)
                locationUpdateCounter = 0
            }
        }
    }

here is my override init() where I set and start location tracking:

    override init() {
        super.init()
        self.locationManager.delegate = self

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.delegate = self
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.showsBackgroundLocationIndicator = true
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        startUpdatingtLocation()
        LogEvent.print(module: "LocationManager.init()", message: "init finished")
    }
    func startUpdatingtLocation() {
        let authorizationStatus = locationManager.authorizationStatus
        if authorizationStatus == .authorizedAlways {
            locationManager.startMonitoringSignificantLocationChanges()
            locationManager.startUpdatingLocation()
        } else if authorizationStatus == .authorizedWhenInUse {
            locationManager.startMonitoringSignificantLocationChanges()
            locationManager.startUpdatingLocation()
        }
        LogEvent.print(module: "LocationManager.startUpdatingLocation", message: "Location tracking started...")
    }
    func saveLocation(location: CLLocation) {
        do {
            // Access the sharedModelContainer
            guard let container = AppEnvironment.sharedModelContainer else {
                print("ModelContainer has not been initialized.")
                return
            }
            
            let context = ModelContext(container)
            
            let entry = GpsJournalSD(
                timestamp: Date(),
                longitude: location.coordinate.longitude,
                latitude: location.coordinate.latitude,
                speed: location.speed
            )
            
            context.insert(entry)
            
            print("Location saved: \(entry.timestamp) \(formatMPH(convertMPStoMPH( entry.speed))) mph")
        }
    }

I also have location updates allowed in Background Modes as well as the privacy locations set in the pinfo.list.

Here is where I see when I save. It's filling up my data model with duplicates:

Location saved: 2024-02-25 16:48:31 +0000 6 mph
Location saved: 2024-02-25 16:48:31 +0000 6 mph

Location saved: 2024-02-25 16:48:36 +0000 21 mph
Location saved: 2024-02-25 16:48:36 +0000 21 mph

Location saved: 2024-02-25 16:48:41 +0000 36 mph
Location saved: 2024-02-25 16:48:41 +0000 36 mph
0

There are 0 best solutions below