Server-Sent Events in Swift: Real-Time Data Streaming Without WebSocket

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why SSE is Your New Best Friend



Imagine: you're sitting in a cozy café, drinking coffee, while your iOS app receives fresh currency exchange rates, notifications about new messages, or data from IoT device sensors in the background. And all this — without constant pings to the server, without draining the battery, and without complex protocols like WebSocket. Meet: Server-Sent Events (SSE) in Swift — a technology that makes data streaming so simple, you'll wonder why you haven't used it before.



In this article, we'll break down how to implement Server-Sent Events in Swift for iOS, macOS, watchOS, and tvOS. You'll learn why SSE is often more convenient than WebSocket, how to write your own SSE client from scratch, and what pitfalls await beginners. Let's go!



What Are Server-Sent Events and Why Do You Need Them?



Server-Sent Events is a W3C standard that allows a server to send data to a client over a single HTTP connection. Unlike WebSocket, SSE works only in one direction (server → client), but this is precisely what makes it ideal for tasks where bidirectional communication is not needed.



When to Choose SSE Over WebSocket?

  • Notifications and alerts — the server sends events, the client only reads.
  • Streaming data — stock quotes, server metrics, GPS tracking.
  • News feeds — Twitter-like updates.
  • Progress tracking — file uploads, video processing.


The main advantage of SSE over WebSocket is simplicity. You don't need a separate protocol; regular HTTP is sufficient. This means any server running Python, Node.js, or Go can send events to your Swift application without extra libraries.



How SSE Works: Breaking Down the Protocol



The server sends a regular HTTP response with the header Content-Type: text/event-stream. The data is formatted as follows:



event: messagedata: {"text": "Hello, world!"}id: 42

event: updatedata: {"count": 10}retry: 3000


Key fields:

  • event — event type (optional).
  • data — event body (can be multi-line).
  • id — identifier for reconnection.
  • retry — time in ms before reconnecting on error.


Each event is separated by two newline characters

. Simple, right?



Creating an SSE Client in Swift: From Simple to Advanced



The standard Foundation library does not have a ready-made class for SSE, but writing your own takes 15 minutes. We'll use URLSession with a delegate that handles streaming data.



Step 1: Basic EventSource Class



import Foundation

final class EventSource: NSObject { private var url: URL private var session: URLSession? private var task: URLSessionDataTask? private var currentData = Data() private var lastEventId: String? var onEvent: ((String, String) -> Void)? // event, data var onError: ((Error) -> Void)? var onOpen: (() -> Void)? init(url: URL) { self.url = url super.init() } func connect() { var request = URLRequest(url: url) request.setValue("text/event-stream", forHTTPHeaderField: "Accept") if let lastId = lastEventId { request.setValue(lastId, forHTTPHeaderField: "Last-Event-ID") } let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = TimeInterval(INT_MAX) config.timeoutIntervalForResource = TimeInterval(INT_MAX) session = URLSession(configuration: config, delegate: self, delegateQueue: nil) task = session?.dataTask(with: request) task?.resume() } \

Blogs

Book Recommendations