WebSocket Libraries for Swift (iOS/macOS): Starscream and URLSessionWebSocketTask
WebSocket is a protocol that provides full-duplex communication between a client and a server over a single TCP connection. In the Swift ecosystem (iOS/macOS), there are two main approaches for working with WebSocket: the native implementation URLSessionWebSocketTask (available since iOS 13/macOS 10.15) and the popular third-party library Starscream. Both allow you to create reactive real-time applications: chats, ticker feeds, multiplayer games, etc.
Native Implementation URLSessionWebSocketTask
With the release of iOS 13, Apple added built-in WebSocket support to the Foundation framework. This eliminates the need to add third-party dependencies if your application targets modern OS versions.
Key Features:
- Fully asynchronous operation via
async/awaitor callbacks - Automatic connection lifecycle management
- Support for
closeCode,closeReasonfor proper termination - Built-in integration with
URLSession(timeout support, caching policies)
Example of connecting and sending a message:
import Foundation
class WebSocketManager { private var webSocketTask: URLSessionWebSocketTask? private let session = URLSession.shared func connect() { guard let url = URL(string: "wss://echo.websocket.org") else { return } webSocketTask = session.webSocketTask(with: url) webSocketTask?.resume() receiveMessage() } func sendMessage(_ text: String) { let message = URLSessionWebSocketTask.Message.string(text) webSocketTask?.send(message) { error in if let error = error { print("Send error: \\(error.localizedDescription)") } } } private func receiveMessage() { webSocketTask?.receive { [weak self] result in switch result { case .success(let message): switch message { case .string(let text): print("Received: \\(text)") case .data(let data): print("Received binary data: \\(data)") @unknown default: fatalError() } // Continue listening self?.receiveMessage() case .failure(let error): print("Receive error: \\(error)") // Possibly reconnect } } } func disconnect() { webSocketTask?.cancel(with: .normalClosure, reason: nil) }}Starscream — Flexible and Proven Library
Starscream is an open-source WebSocket library for Swift, written by Dalton Cherry and maintained by the community. It works on iOS, macOS, tvOS, and watchOS, starting from older versions (iOS 8+). Starscream provides more control over the connection and supports additional features such as compression (permessage-deflate) and custom headers.
Installation via Swift Package Manager:
// In Package.swift or via Xcode: File → Swift Packages → Add Package Dependency.package(url: "https://github.com/daltoniam/Starscream.git", from: "4.0.0")Key Features:
- Support for
WebSocketDelegatefor all events (connection, data reception, errors, disconnection) - Manual ping/pong management to maintain the connection
- Ability to send binary data (Data) and strings (String/UTF-8)
- Support for SSL/TLS and self-signed certificates