I want to send user current Location
to a server in every 15 minutes. When the app is in the foreground the timer
is running but when the app is in background timer is not running. I searched a lot but did not find any solution. Can you please tell me what I do. I am using below code for background location sync but it's not working.
var locationManager = CLLocationManager()
var currentLocation: CLLocation?
var timer : Timer?
var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?
func getCurrentLocation()
{
// Do any additional setup after loading the view, typically from a nib.
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
//
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
let timer = Timer.scheduledTimer(withTimeInterval: 10.0, repeats: true) { (timer) in
self.locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
print("locations = \(locations)")
if let location = locations.last
{
print("location\(String(describing: location.coordinate))")
currentLocation = location
locationManager.stopUpdatingLocation()
}
}