LongRunningIntent
An interface you use to extend the background execution time of an app intent that performs a long-running task.
Declaration
protocol LongRunningIntent : ProgressReportingIntentMentioned in
Overview
This protocol allows an app intent to run for an extended period of time in the background. When a task runs in the background, the system traditionally gives it up to 30 seconds to finish its task. For some types of tasks, this amount of time can be insufficient to complete the task. For example, file operations, data synchronization, machine learning inference, and data processing tasks can take longer if they operate on a sufficiently large amount of data. If your app intent performs a task that might exceed the built-in time limits, incorporate this protocol and use its methods to perform that task.
In the implementation of your app intent, place the code for your task inside one of the methods this protocol offers. The methods of this protocol work with the system to extend the amount of time your code has to run. While your code runs, the system requires you to report progress regularly, which you do using the progress property of the inherited ProgressReportingIntent protocol. If you don’t update this property regularly, the system can cancel the background runtime extension and end your task prematurely.
The following example shows the implementation of an app intent that uploads a file. The implementation uploads the file in chunks, and updates the progress property after each chunk.
struct UploadFileIntent: LongRunningIntent {
static var title: LocalizedStringResource = "Upload Large File"
@Parameter(title: "File")
var file: IntentFile
func perform() async throws -> some IntentResult & ReturnsValue<String> {
// Use performBackgroundTask - zero required parameters!
let result = try await performBackgroundTask {
// This code runs with extended execution time
progress.totalUnitCount = 100
progress.localizedDescription = "Uploading file"
for chunk in 0..<100 {
try Task.checkCancellation()
await uploadChunk(chunk)
progress.completedUnitCount = Int64(chunk + 1)
progress.localizedAdditionalDescription = "\(chunk + 1)% complete"
}
return "Upload complete!"
}
return .result(value: result)
}
private func uploadChunk(_ chunk: Int) async {
// Simulate uploading a chunk
}
}