Search code examples
iphoneiosxcodebackgroundforeground

Keep an iOS app running in foreground


I would like to know if there's a way to keep an app running in foreground, during a specific interval time.

I have a thread running exactly during 3 minutes and I need that the user cannot leave the app. If such a thing is not possible I'm going to ask another question.

I could let that the user set the app in background mode because I use the applicationDidEnterBackground:(UIApplication *)application method to save the data I need but if the user clicks the power button, how could I save the data?

The applicationWillTerminate:(UIApplication *)application would be called? Is there any solution?


Solution

  • You might want to look into beginBackgroundTaskWithExpirationHandler, which lets your app request additional processing time to complete tasks when your app is backgrounded.

    That said, what you're looking to do isn't advisable. You should make sure your app can recover from your three minute task in case of unexpected termination or failure. For example, your app could crash unexpectedly or terminate due to low memory - in these cases, you won't get any callbacks to applicationWillTerminate or applicationDidEnterBackground.

    So my recommendation would be to look at using iOS's background task support to have your save continue in the background if the user leaves the app, but also ensure that in the event your app be terminated by the system without warning your task is recoverable / can safely be rewound.