Mo Moosa Mo Moosa - 1 year ago 64
iOS Question

Execute a line of code after a certain amount of time in the background on iOS 7

To provide some context, the application I'm working on allows the user to record a series of events along a timeline. One important piece of feedback we received from beta testers was that when the user exits the app while recording they'd like the timer to keep up to date for a set amount of time.

For example if the user has recorded 5 minutes and then leaves the app to check an email for 20 seconds, the timer should be 5:20, but it was actually still 5 minutes.

So we've fixed that - the app now would now show 5:20, and this works in the background.

However we can't figure out a way to stop it after a certain amount of time. A user might want the timer to resume if the app is in the background for a short amount of time, but if you leave it in the background for 30 minutes, the timer will update, and I'd like to be able to give the users an optional cut-off time so that the app pauses after a set amount of time.

I've tried listening out for UIApplicationDelegate notifications, but the problem is I'm looking for a point between applicationDidEnterBackground: and applicationWillTerminate, but there's sadly nothing to cater for my needs there.

To summarise, I'd like to have a grace period of 30-60 seconds from applicationWillResignActive: to determine whether or not to pause the timer, or let it keep going.

Would this be possible?

Thanks in advance

Answer Source

It's generally a bad idea to assume your app will be running in the background.

A better way to think about it IMO would be to set a variable to the current time in applicationDidEnterBackground: and check the time interval to now in applicationWillBecomeActive: :

  • If the interval is bigger that your grace period, have the time backup to when the app was paused.
  • If it is smaller, update it as if the app was never in the background.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download