<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/URLSession/webSocketTask(with:)-mtks",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSURLSession(im)webSocketTaskWithRequest:"
  },
  "title" : "webSocketTask(with:)"
}
-->

# webSocketTask(with:)

Creates a WebSocket task for the provided URL request.

```
func webSocketTask(with request: URLRequest) -> URLSessionWebSocketTask
```

## Parameters

`request`

A URL request that indicates a WebSockets endpoint with which to connect.

## Discussion

You can modify the request’s properties prior to calling [`resume()`](/documentation/Foundation/URLSessionTask/resume()) on the task. The task uses these properties during the HTTP handshake phase.

To add custom protocols, add a header with the key `Sec-WebSocket-Protocol`, and a comma-separated list of protocols you want to negotiate with the server. The custom HTTP headers provided by the client remain unchanged for the handshake with the server.

---

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)