简体   繁体   中英

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)
UIApplication.SharedApplication.EndBackgroundTask(_timerBackgroundTaskId.Value);

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?

In fact, the app was killed because I was running a background task longer than 3 minutes, which is the limit. The solution to my problem was as easy as limiting the task to 3 minutes max.

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 (ie: 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, to keep the app state you´ve got 2 options:

  1. End the task before 3 minutes
  2. Implement a restoring strategy. iOS itself provides a built-in API for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM