Tracking User Activity (Driving/Walking) Periodically with Background Execution (Background state & Terminated state)

I'm working on an application where, once the user starts driving, I need to periodically check their activity every 2.5 minutes (150 seconds) to determine whether they are still driving, walking, or have stopped. If they are still driving, I want to keep rescheduling the task until the user is no longer in a driving state.

Currently, I'm using startMonitoringSignificantLocationChanges to wake the app when the user's location changes, which works as expected. However, the activity detection stops after the first result is received, and I can't continue tracking the user's activity in the background (or after the app is killed from the app switcher).

Here's my approach:

  • After receiving a significant location change, I start tracking the user’s activity to check if they are driving or have stopped.
  • I reschedule this task every 2.5 minutes as long as the user remains in a driving state.
  • I need this process to run even when the app is in the background or terminated by the user.

Question: Is it possible to keep activity detection running periodically after receiving a location change, even when the app is in the background or terminated? What is the recommended way to implement this?

I would appreciate any suggestions or best practices for achieving this functionality.

This convoluted solution to work around the limitations is both fragile and unnecessary.

First, you need to accept the fact that there is no API that will allow you to do anything in the background at an exact schedule (like the 2.5 minutes). For location updates, your only viable solution is to use startUpdatingLocation() receive the location updates every second, and then do whatever it is you need to do every 150 seconds.

But while this will work when the app is in the foreground and background, it will not work if it gets terminated.

There is a new CoreLocation API which you can use that is both immune to app being terminated, but also will automatically stop and start location updates of the user stops and then starts. While the user is moving and you are receiving location updates, you can check if the conditions are right for your use case (driving or not, etc.).

The new API is described at Receive location updates in the background

WWDC24 Session What’s new in location authorization explains this new API and the latest improvements, along with some example code.


Argun Tekant /  DTS Engineer / Core Technologies

Tracking User Activity (Driving/Walking) Periodically with Background Execution (Background state & Terminated state)
 
 
Q