Background task in iOS action extension

后端 未结 4 1459
梦毁少年i
梦毁少年i 2021-02-13 02:13

I\'m working on an action extension for an app which prepares some data for the user and then uses MailCore2 to send this information to a SMTP server. Preparing data is done ve

4条回答
  •  余生分开走
    2021-02-13 02:44

    After many tests and failures, I found the following solution to execute a long performing task in the background of an extension. This works as expected, even if the extension is already finished:

    func performTask()
    {
        // Perform the task in background.
        let processinfo = ProcessInfo()
        processinfo.performExpiringActivity(withReason: "Long task") { (expired) in
            if (!expired) {
                // Run task synchronously.
                self.performLongTask()
            }
            else {
                // Cancel task.
                self.cancelLongTask()
            }
        }
    }
    

    This code uses ProcessInfo.performExpiringActivity() to execute the task in another thread. It’s important that the task in performLongTask() is executed synchronously. When the end of the block is reached, the thread will terminate and end the execution of your task.

    A similar approach is also working in the main app. It's described in detail in a small summary for background tasks in iOS.

提交回复
热议问题