---
title: "onBackgroundURLSessionEvents(matching:_:)"
framework: swiftui
role: symbol
role_heading: Instance Method
path: "swiftui/widgetconfiguration/onbackgroundurlsessionevents(matching:_:)-fw6x"
---

# onBackgroundURLSessionEvents(matching:_:)

Adds an action to perform when events related to a URL session with a matching identifier are waiting to be processed.

## Declaration

```swift
@MainActor @preconcurrency func onBackgroundURLSessionEvents(matching matchingString: String, _ urlSessionEvent: @escaping (String, @escaping () -> Void) -> Void) -> some WidgetConfiguration

```

## Parameters

- `matchingString`: The identifier of a URL session to monitor for events.
- `urlSessionEvent`: A closure that takes a string identifier and a closure called completion as parameters.

## Return Value

Return Value A widget that triggers urlSessionEvent when events are generated for a URLSession with the specified identifier.

## Discussion

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 matching parameter to determine if a corresponding URLSession object exists. If the system hasn’t terminated your widget extension, maintain a reference to the same URLSession object you used for the original background network request. If the system terminated your widget extension, use the identifier to create a new URLSession object so it can receive the events. You might consider lazily initializing, and caching, the URLSession objects 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 completion closure of urlSessionEvent to invoke it after the system delivers all events. After the system calls the URLSession delegate’s urlSessionDidFinishEvents(forBackgroundURLSession:) method, invoke the completion closure.
