Prevent iOS from killing my app after 3 minutes

好久不见. 提交于 2020-01-03 07:05:09

问题


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?


回答1:


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 (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, 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.


来源:https://stackoverflow.com/questions/42035461/prevent-ios-from-killing-my-app-after-3-minutes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!