Press "Enter" to skip to content

Battery efficient background time-based location updates on iOS

When tracking location updates on iOS, there are certain scenarios where we want to get regular location updates based on time as if used wisely, it is more battery efficient than standard location updates.

Standard location updates keep GPS always on, causing considerable battery drain, while a time-based approach requests a one-time location update, GPS will turn on when the timer triggers the event handler and then it will turn off until the event is fired again.

In this article, I will show you how to get background time-based location updates by using a DispatchSourceTimer. It is the lowest level background timer API that gives you more control over the time interval and provides adjustments parameters for energy efficiency.

Let’s Start

1. Add required permissions

Add location permissions and enable location updates background mode in Info.plist

2. Create a DispatchSource.Timer

Create a DispatchSource.Timer instance in a background queue. Set the EventHandler which is the action that will be fired when the timer reaches the time interval.

3. Set the timer parameters and resume it.

Set the timer schedule time, repetition interval, and the leeway interval which is the maximum amount of time that the system may delay the delivery of the timer event to improve power consumption. For more information, please check this.

Personally, I recommend setting the timer repetition interval from 30 seconds and the leeway at least twice that interval (leeway should always be greater than the repetition interval). Keep in mind that the higher these parameters are, the less power consumption you will get, so please set them according to your scenario.

4. Test it!

I created a simple ViewController with a button that triggers the StartTimer method when tapped.

You can check the full source code here.

References

Happy Location Updates!

3 Comments

  1. Nidhin Nidhin

    can you give me a sample for android

  2. samir samir

    when the app is totally closed(not in the background) then It will fetch the location?

  3. Mina Girgis Mina Girgis

    Thank for the great post
    But i have a question… is this more efficient than using background refresh… please advise with a sample project of location updates using background app refresh

Comments are closed.