My background task needs more time

I'm working on a screen where the goal is for the user to walk for 6 minutes while the app times them and measures the distance walked. I'm using CMPedometer to track the walking distance and a repeating 1-second Timer to count down the time.

This works fine as long as the app is in the foreground, but I'd like my user to be able to lock their phone and put it away while they walk. I used UIApplication.shared.beginBackgroundTask, but it doesn't provide enough time. It usually only gives me around 30 seconds. I also tried calling UIApplication.shared.beginBackgroundTask again or calling it once every time the timer ticks, with no better result.

How can I accomplish my goal here?

Replies

I’ve not used this API but it appears to keep track of historical data and doesn’t require active monitoring from the app? Unless I’m reading this wrong. It looks like you just need a timer and then if the app is shut down, pass the remaining time to a push notification to alert the user. Even if it could be done as a background process, the user has the option to turn that off. If they don’t understand why or forget, they may do that.

  • Thanks. I think I get it now. iOS is just always collecting pedometer data in the background regardless of whether I’m asking for it? So I can just stop requesting updates and shut off my timer and when my app wakes up again I ask for the data I missed. This is very convenient if true.

  • Yes and you can give it the appearance of working in the background by adding an observer for UIApplication.willResignActiveNotification and UIApplication.didBecomeActiveNotification. Maybe .willTerminateNotification as well. From those functions, either schedule push notifications or remove them and carry on with the program.

Add a Comment