<!--
{
  "availability" : [
    "iOS: 14.0.0 -",
    "iPadOS: 14.0.0 -",
    "macCatalyst: 14.0.0 -",
    "macOS: 11.0.0 -",
    "visionOS: 26.0.0 -",
    "watchOS: 9.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "SwiftUI",
  "identifier" : "/documentation/SwiftUI/WidgetConfiguration/onBackgroundURLSessionEvents(matching:_:)-2e152",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "SwiftUI"
    ],
    "preciseIdentifier" : "s:7SwiftUI19WidgetConfigurationP0C3KitE28onBackgroundURLSessionEvents8matching_QrSbSScSg_ySS_yyctctF"
  },
  "title" : "onBackgroundURLSessionEvents(matching:_:)"
}
-->

# onBackgroundURLSessionEvents(matching:_:)

Adds an action to perform when events related to a URL session identified by a
closure are waiting to be processed.

```
@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
`identifier` and a closure called `completion`.

## 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:

1. Use the `identifier` 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.
2. Store a reference to the `completion` closure to invoke it after the
   system delivers all events.
3. After the system calls the `URLSession` delegate’s
   <doc://com.apple.documentation/documentation/foundation/urlsessiondelegate/urlsessiondidfinishevents(forbackgroundurlsession:)>
   method, invoke the `completion` closure.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)