onBackgroundURLSessionEvents(matching:_:)
Adds an action to perform when events related to a URL session identified by a closure are waiting to be processed.
Declaration
@MainActor @preconcurrency func onBackgroundURLSessionEvents(matching matchingBlock: ((String) -> Bool)? = nil, _ urlSessionEvent: @escaping (String, @escaping () -> Void) -> Void) -> some WidgetConfiguration
Parameters
- urlSessionEvent:
A closure that takes a string parameter called
identifierand a closure calledcompletion.
Return Value
A widget that triggers urlSessionEvent when events are generated for a URLSession with the specified identifier.
Discussion
When a widget initiates a background network request, the system delivers events related to the request directly to the widget extension instead of the containing app. To process the events, do the following:
Use the
identifierparameter to determine if a correspondingURLSessionobject exists. If the system hasn’t terminated your widget extension, maintain a reference to the sameURLSessionobject you used for the original background network request. If the system terminated your widget extension, use the identifier to create a newURLSessionobject so it can receive the events. You might consider lazily initializing, and caching, theURLSessionobjects in a central location so that your code works regardless of whether your extension remains active, is suspended, or is terminated.Store a reference to the
completionclosure to invoke it after the system delivers all events.After the system calls the
URLSessiondelegate’s urlSessionDidFinishEvents(forBackgroundURLSession:) method, invoke thecompletionclosure.