JacobJ JacobJ - 6 months ago 9
Swift Question

How do I discourage iOS from terminating app while doing a critical operation?

I have an application that communicates with custom hardware over BLE. In normal circumstances, I want my application to terminate quickly when a user presses the home button. However, when my application is in the middle of updating firmware on my custom hardware, I want to dissuade iOS from terminating the application. This firmware operation will take about five minutes from start to finish. I know there is no way to prevent iOS from terminating the app absolutely, but can I do anything to dissuade it from terminating my application while it is doing its firmware update operation?

Rob Rob

If you need 3 minutes or less, you can use beginBackgroundTaskWithName:expirationHandler: when doing the update, so that the app will request time to continue to run in the background in order to complete the task even if the user hits the home button. The problem is that it only gives you 3 minutes, not more than that.

Given that 3 minutes is apparently not enough for you to complete your upload, if you go down this road, I'd suggest combining this will some very serious looking message on the screen telling the user to not leave the app. You could also, when the app is about to enter background (applicationDidEnterBackground), schedule a local notification that will alert the user to return to the app or face serious consequences if they don't.

Even better, you might be able to declare the app as one that requires a proper background mode. For example, there are dedicated background modes bluetooth-central or bluetooth-peripheral that might be applicable. Then the three minute limitation doesn't apply. See Declaring Your App’s Supported Background Tasks in the App Programming Guide for iOS.