I want the location to update every 3 minutes. The background task works after 3 minutes the first time, but doesn't restart after that. I need it to happen repeatedly and not once.
override func viewDidLoad()
{
super.viewDidLoad()
timer.invalidate()
timer = Timer.scheduledTimer(timeInterval: 179, target: self, selector: #selector(someBackgroundTask), userInfo: nil, repeats: true);
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
if CLLocationManager.locationServicesEnabled()
{
if status == CLAuthorizationStatus.notDetermined
{
locationManager.requestAlwaysAuthorization()
}
}else {
print("locationServices disenabled")
}
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
mapView.delegate = self
registerBackgroundTask()
}
func someBackgroundTask(timer:Timer) {
DispatchQueue.global(qos: .background).async {
self.locationManager.startUpdatingLocation()
timer.invalidate()
timer.fire()
self.registerBackgroundTask()
}
}
func registerBackgroundTask() {
backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
self?.someBackgroundTask(timer: (self?.timer)!)
self?.endBackgroundTask()
}
assert(backgroundTask != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
print("Background task ended.")
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}