My problem was unrelated to the main problem discussed here, so with the piece of code below, any IOS release below or above 16.4 work.
Use case for the example: I print latitude and longitude every 30s.
This code so far worked for +24h like a charm, whatever the device moves or not, whatever the app is in the foreground or in the background, whatever the screen is on or off.
Of course you must select 'Location updates' for 'Background modes' in 'Signing & Capabilities' of your project's Target. But this is obvious no :)
class TestLocation: UIViewController, CLLocationManagerDelegate{
@objc var locationManager: CLLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Configure location manager
locationManager.delegate = self
// requestAlwaysAuthorization() could be done before in your app, which is the case for me but for the example, I put it here (indeed requestAlwaysAuthorization() MUST be
done when the app starts to avoid any crash, if you do some stuff before doing startUpdatingLocation())
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.showsBackgroundLocationIndicator = true
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let currentLocation = locations.last(where: { $0.horizontalAccuracy >= 0 }) else { return }
if let lastUpdateDate = lastLocationUpdateDate, Date().timeIntervalSince(lastUpdateDate) < 30 {
return
}
else{
print("Latitude: \(currentLocation.coordinate.latitude), Longitude: \(currentLocation.coordinate.longitude)")
lastLocationUpdateDate = Date()
}
}
}
Hope it helps