xleon xleon - 4 years ago 75
iOS Question

Prevent iOS from killing my app after 3 minutes

To avoid implementing a persistent caching logic of a whole navigation stack I want to keep my app "alive" (at least for 2 hours) even in the background, so when the user reopens the app it is where it was before going to sleep.

I tried with a background task:

_timerBackgroundTaskId = UIApplication.SharedApplication.BeginBackgroundTask(() =>
// Run some dummy code here. Shouldn´t this prevent the task from actually stopping?
var remaining = UIApplication.SharedApplication.BackgroundTimeRemaining;
this.Log().Debug($"Expiration. Remaining: {remaining}. Timer seconds left: {_secondsLeft}");
// I´m actually using the timer for something :)
_nsTimer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1), delegate { TimerTick(); });

// later on (after 3 minutes)

No matter what I try, after 3 minutes iOS kills the app.
Some answers in SO tell how to do it with a fake/silent background sound, but I don´t want any trouble with Apple reviews.

Any advice?

Answer Source

The solution to my problem was as easy as doing exactly nothing.

By default iOS won´t ever kill your app, unless the device runs severely out of memory.

The 3 minutes limit is applied only when you run some task in the background (i.e: UIApplication.SharedApplication.BeginBackgroundTask) to prevent battery drain.

If you don´t start any background task before the app goes to background, the app will always be there, keeping the state (I´ve tested this waiting for hours).

In my case I was using a background task to keep a countdown/alarm working. But I´ve just found a workaround scheduling local notifications.

If you MUST run a background task, the proper way to keep the navigation stack state is implementing a restoring strategy. iOS itself provides a built-in API for it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download