1

I want to index the part of content through background thread each time the user run the app, but when i pressing 1 time Home button in middle of background task and app goes to background , this message i received : "Terminated due to signal 9". i want to index part of content that is possible when app is in foreground mode but in background thread without crashing the app. My main problem is why the app killed through middle of task running in background thread, even that task will be only print string in console! how should i handle this scenario?

1 Answers1

0

You would have to start a background task and end it when you are done with your work something like this

var bgTask: UIBackgroundTaskIdentifier?

Add bgTask as your objects property and then

let application = UIApplication.shared

bgTask = application.beginBackgroundTask(withName: "name", expirationHandler: {
    self.endBackgroundTask()
})

DispatchQueue.global(qos: .background).async {[weak self] in
    //do your stuff here

    self?.endBackgroundTask()
}

Add endBackgroundTask() method

func endBackgroundTask() {
    if bgTask != UIBackgroundTaskInvalid {
        UIApplication.shared.endBackgroundTask(bgTask!)
        bgTask = UIBackgroundTaskInvalid
    }
}

You can read more about this here

https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

Ladislav
  • 7,223
  • 5
  • 27
  • 31