Swift Network Programming: From Sockets to 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

Swift Network Programming: From Simple to Complex

\n\n

When you first open Xcode and see an empty project, it seems like the real magic of network interaction is still far away. But believe me: Swift network programming is not rocket science, but a very tangible tool that turns a local application into part of the global internet. Today we will break down how to make your application "talk" to servers, exchange data, and do it beautifully.

\n\n

I will show you not just dry definitions, but real-life scenarios from an iOS developer's experience. You will learn how Swift networking works at a low level (sockets) and at a high level (URLSession). And at the end — a bonus: how to connect WebSocket for a live chat. Let's go!

\n\n

Understanding the Basics: How Networks Work in the Swift World

\n\n

Before writing code, let's understand the concepts. Swift network programming is based on the same principles as in any other language: client-server architecture, TCP/UDP protocols, IP addresses, and ports. But there is a nuance — the Apple ecosystem offers its own frameworks that make a developer's life easier.

\n\n

Key Technologies for Working with Networks in Swift

\n\n
    \n
  • URLSession — the main tool for HTTP/HTTPS requests. Works with REST API, file downloads, background tasks.
  • \n
  • Network.framework — low-level access to sockets, TCP/UDP. Introduced in iOS 12, replaced the old CFNetwork.
  • \n
  • WebSocket (URLSessionWebSocketTask) — for real-time bidirectional communication.
  • \n
  • CFStream — an old but still active way to work with data streams.
  • \n
\n\n

Personally, I recommend starting with URLSession — it's like driving a car with an automatic transmission. And when you want "manual" — switch to Network.framework.

\n\n

URLSession: Your Best Friend in Swift Network Programming

\n\n

Let's start with the most popular tool. URLSession Swift is a powerful framework for sending and receiving data over the network. It supports caching, authentication, background downloads, and much more.

\n\n

Basic GET Request

\n\n

Imagine your application needs to display a list of users from a server. Here's how it's done:

\n\n
import Foundation\n\n// 1. Create a URL\nguard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else {\n    fatalError("Invalid URL")\n}\n\n// 2. Create a task\nlet task = URLSession.shared.dataTask(with: url) { data, response, error in\n    // 3. Handle errors\n    if let error = error {\n        print("Error: \\(error.localizedDescription)")\n        return\n    }\n    \n    // 4. Check the server response\n    guard let httpResponse = response as? HTTPURLResponse,\n          (200...299).contains(httpResponse.statusCode) else {\n        print("Invalid status code")\n        return\n    }\n    \n    // 5. Work with data\n    if let data = data {\n        do {\n            let users = try JSONDecoder().decode([User].self, from: data)\n            print("Received \\(users.count) users")\n        } catch {\n            print("Parsing error: \\(error)")\n        }\n    }\n}\n\n// 6. Start the task\ntask.resume()
\n\n

Note: task.resume() is mandatory! Otherwise, the request will never execute. This is a common mistake for beginners in Swift network programming.

\n\n

POST Request with Body

\n\n

Now let's send data to the server:

\n\n
func createUser(name: String, email: String) {\n    guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else {\n        return\n    }\n    \n    var request = URLRequest(url: url)\n    request.httpMethod = "POST"\n    request.setValue("application/json", forHTTPHeaderField: "Content-Type")\n    \n    let body                

Blogs

Book Recommendations