How do I use URLSessionWebSocketTask for WebSockets in Swift?

Learn how to use URLSessionWebSocketTask for establishing WebSocket connections in Swift. This guide provides a comprehensive example that demonstrates how to connect to a WebSocket server, send messages, and receive messages asynchronously.
WebSocket, Swift, URLSession, URLSessionWebSocketTask, iOS Development, Real-time Communication
import Foundation

// Create a URLSession
let url = URL(string: "wss://example.com/socket")!
let urlSession = URLSession(configuration: .default)

// Create a WebSocket task
let webSocketTask = urlSession.webSocketTask(with: url)

// Function to receive messages
func receiveMessages() {
    webSocketTask.receive { result in
        switch result {
        case .failure(let error):
            print("WebSocket error: \(error)")
        case .success(let message):
            switch message {
            case .string(let text):
                print("Received text: \(text)")
            case .data(let data):
                print("Received data: \(data)")
            @unknown default:
                fatalError()
            }
            // Continue receiving messages
            receiveMessages()
        }
    }
}

// Start the WebSocket connection
webSocketTask.resume()
receiveMessages()

// Sending a message
let message = URLSessionWebSocketTask.Message.string("Hello, WebSocket!")
webSocketTask.send(message) { error in
    if let error = error {
        print("Error sending message: \(error)")
    } else {
        print("Message sent!")
    }
}

WebSocket Swift URLSession URLSessionWebSocketTask iOS Development Real-time Communication