0

I have 3 Background Queue tasks running on app launch. They take approximately 25sec to complete. There is no memory issues, nor an issue with the tasks themselves, the tasks simply go through a database for filtering/reading data purposes (SQLite).

If I minimise the app whilst the tasks are running, the app is killed within 3sec, as any time I go back to the app after 3 sec the app starts again. I get the "Message from debugger: Terminated due to signal 9" as soon as I minimise the app. I use Swift and iOS14, is there a way to complete 30sec or less background SQLite DB tasks with the app not released from memory? Or just pause/kill the tasks to prevent killing the app?

I run my tasks using the DispatchQueue Extension:

extension DispatchQueue {

static func background(delay: Double = 0.0, background: (()->Void)? = nil, completion: (() -> Void)? = nil) {
    DispatchQueue.global(qos: .background).async {
        background?()
        if let completion = completion {
            DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
                completion()
            })
        }
    }
}

static func backgroundFast(delay: Double = 0.0, background: (()->Void)? = nil, completion: (() -> Void)? = nil) {
    DispatchQueue.global(qos: .default).async {
        background?()
        if let completion = completion {
            DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
                completion()
            })
        }
    }
}

}
Paul
  • 183
  • 1
  • 12
  • You need to use the background task API. There is sample code from Apple here https://developer.apple.com/documentation/backgroundtasks/refreshing_and_maintaining_your_app_using_background_tasks – Paul.s Apr 08 '21 at 21:38
  • Isn't that for scheduling background tasks when the app enters background? I'm happy with my tasks pausing and just running when the app is visible. I just want to prevent the app from terminating/rebooting every time it's minimised. – Paul Apr 08 '21 at 22:17
  • What does "minimised" mean? – matt Apr 09 '21 at 02:19

1 Answers1

1

If you only need 25 seconds for your backgound tasks to complete you should be able to call the beginBackgroundTask(withName:expirationHandler:) method in response to your app delegate's applicationDidEnterBackground(_:) method being called.

That will give you up to 3 minutes of background time.

See this article for Apple for more information.

https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/extending_your_app_s_background_execution_time

One thing to be aware of (Quoting Apple's docs)

Warning

If you are using scenes (see Scenes), UIKit will not call this method. Use sceneDidEnterBackground(_:) instead to perform any final tasks. UIKit posts a didEnterBackgroundNotification regardless of whether your app uses scenes.

Duncan C
  • 128,072
  • 22
  • 173
  • 272