Posted in

Websocket in iOS – Swift basics

websocket

We can have a quick basic understanding of Websocket in iOS. A WebSocket connection is a bi-directional, full-duplex communication protocol over a single, long-lived TCP connection. Unlike traditional HTTP, where a client must initiate every request and wait for a response, WebSockets allow both the client and server to send messages to each other at any time.

What is a WebSocket in iOS?

  • Protocol: ws:// or wss:// (secure)
  • Persistent: Keeps the connection open between client and server.
  • Real-time: Ideal for apps needing real-time data (e.g., chat, games, stock prices).
  • Low-latency: No need to re-establish connection on each request (unlike HTTP).

Where it is used in mobile application ?

In mobile apps (iOS/Android), WebSocket is typically used for:

  • Chat apps – Real-time messaging.
  • Live notifications – Push updates from server.
  • Online multiplayer games – Real-time game state sync.
  • Live tracking apps – GPS location updates.
  • Stock/crypto price monitoring – Instant data updates.
websocket connection

WebSocket vs HTTP APIs (REST)

FeatureHTTP (REST API)WebSocket
ConnectionOne request = one responsePersistent connection
CommunicationClient → ServerBi-directional
LatencyHigherLow (no reconnection required)
Real-timePolling or long-pollingNative support
Data PushNo (client pulls)Yes (server pushes)

How to use WebSocket in iOS (Swift) — Basic Example

import Foundation

class WebSocketManager: NSObject {
    var webSocketTask: URLSessionWebSocketTask?

    func connect() {
        let url = URL(string: "wss://example.com/socket")!
        webSocketTask = URLSession(configuration: .default).webSocketTask(with: url)
        webSocketTask?.resume()
        receiveMessage()
    }

    func send(message: String) {
        let msg = URLSessionWebSocketTask.Message.string(message)
        webSocketTask?.send(msg) { error in
            if let error = error {
                print("WebSocket sending error: (error)")
            }
        }
    }

    func receiveMessage() {
        webSocketTask?.receive { [weak self] result in
            switch result {
            case .success(let message):
                switch message {
                case .string(let text):
                    print("Received: (text)")
                default:
                    break
                }
                self?.receiveMessage() // Keep listening
            case .failure(let error):
                print("WebSocket receiving error: (error)")
            }
        }
    }

    func disconnect() {
        webSocketTask?.cancel(with: .goingAway, reason: nil)
    }
}

When to Use WebSocket in a Mobile App?

Use WebSocket when:

  • You need real-time two-way communication.
  • REST API polling is too inefficient.
  • You want lower battery usage compared to frequent polling.

Thank you, Share your thoughts!

I'm a passionate iOS Developer with over 10 years of experience building high-quality iOS apps using Objective-C, Swift, and SwiftUI. I created iostutor.com to share practical tips, tutorials, and insights for developers of all levels.

When I’m not coding, I enjoy exploring new technologies and writing content — from technical guides to stories and poems — with the hope that it might help or inspire someone, somewhere.

Leave a Reply

Your email address will not be published. Required fields are marked *