---
title: "urlSession(_:webSocketTask:didCloseWith:reason:)"
framework: foundation
role: symbol
role_heading: Instance Method
path: "foundation/urlsessionwebsocketdelegate/urlsession(_:websockettask:didclosewith:reason:)"
---

# urlSession(_:webSocketTask:didCloseWith:reason:)

Tells the delegate that the WebSocket task received a close frame from the server endpoint, optionally including a close code and reason from the server.

## Declaration

```swift
optional func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
```

## Parameters

- `session`: The session of the WebSocket task that closed.
- `webSocketTask`: The WebSocket task that closed.
- `closeCode`: The close code provided by the server. If the close frame didn’t include a close code, this value is nil.
- `reason`: The close reason provided by the server. If the close frame didn’t include a reason, this value is nil.

## See Also

### Handling WebSocket lifecycle events

- [urlSession(_:webSocketTask:didOpenWithProtocol:)](foundation/urlsessionwebsocketdelegate/urlsession(_:websockettask:didopenwithprotocol:).md)
