$npx -y skills add dpearson2699/swift-ios-skills --skill ios-networkingBuild, review, or improve networking code in iOS/macOS apps using URLSession with async/await, structured concurrency, and modern Swift patterns. Use when working with REST APIs, downloading files, uploading data, WebSocket connections, pagination, retry logic, request middleware
| 1 | # iOS Networking |
| 2 | |
| 3 | Use URLSession with async/await and structured concurrency for ordinary HTTP, |
| 4 | REST, uploads, downloads, and streaming. Use Network.framework for lower-level |
| 5 | protocols and delegate/task APIs for durable background transfers. |
| 6 | |
| 7 | ## Contents |
| 8 | |
| 9 | - [Core URLSession async/await](#core-urlsession-asyncawait) |
| 10 | - [API Client Architecture](#api-client-architecture) |
| 11 | - [Error Handling](#error-handling) |
| 12 | - [Pagination](#pagination) |
| 13 | - [Network Reachability](#network-reachability) |
| 14 | - [Configuring URLSession](#configuring-urlsession) |
| 15 | - [App Transport Security (ATS)](#app-transport-security-ats) |
| 16 | - [Common Mistakes](#common-mistakes) |
| 17 | - [Review Checklist](#review-checklist) |
| 18 | - [References](#references) |
| 19 | |
| 20 | ## Core URLSession async/await |
| 21 | |
| 22 | URLSession gained native async/await overloads in iOS 15. Prefer these for |
| 23 | foreground data, upload, download, and streaming work. Background URLSession |
| 24 | transfers are the main exception: they still use task/delegate APIs so the |
| 25 | system can deliver events after suspension or relaunch. |
| 26 | |
| 27 | Validate networking policy locally with `URLProtocol` fixtures for valid 2xx, |
| 28 | malformed 2xx, one-time 401 refresh, bounded 429/5xx retry, timeout/offline, |
| 29 | cancellation, and nonretryable 4xx. Inspect headers, status, and error |
| 30 | classification; fix the policy and rerun. Retry only safe/idempotent or |
| 31 | explicitly replayable requests, and never loop token refresh. |
| 32 | |
| 33 | ### Data Requests |
| 34 | |
| 35 | ```swift |
| 36 | // Basic GET |
| 37 | let (data, response) = try await URLSession.shared.data(from: url) |
| 38 | |
| 39 | // With a configured URLRequest |
| 40 | var request = URLRequest(url: url) |
| 41 | request.httpMethod = "POST" |
| 42 | request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 43 | request.httpBody = try JSONEncoder().encode(payload) |
| 44 | request.timeoutInterval = 30 |
| 45 | request.cachePolicy = .reloadIgnoringLocalCacheData |
| 46 | |
| 47 | let (data, response) = try await URLSession.shared.data(for: request) |
| 48 | ``` |
| 49 | |
| 50 | ### Response Validation |
| 51 | |
| 52 | Always validate the HTTP status code before decoding. URLSession does not |
| 53 | throw for 4xx/5xx responses -- it only throws for transport-level failures. |
| 54 | |
| 55 | ```swift |
| 56 | guard let httpResponse = response as? HTTPURLResponse else { |
| 57 | throw NetworkError.invalidResponse |
| 58 | } |
| 59 | |
| 60 | guard (200..<300).contains(httpResponse.statusCode) else { |
| 61 | throw NetworkError.httpError( |
| 62 | statusCode: httpResponse.statusCode, |
| 63 | data: data |
| 64 | ) |
| 65 | } |
| 66 | ``` |
| 67 | |
| 68 | ### JSON Decoding with Codable |
| 69 | |
| 70 | ```swift |
| 71 | func fetch<T: Decodable>(_ type: T.Type, from url: URL) async throws -> T { |
| 72 | let (data, response) = try await URLSession.shared.data(from: url) |
| 73 | |
| 74 | guard let httpResponse = response as? HTTPURLResponse, |
| 75 | (200..<300).contains(httpResponse.statusCode) else { |
| 76 | throw NetworkError.invalidResponse |
| 77 | } |
| 78 | |
| 79 | let decoder = JSONDecoder() |
| 80 | decoder.dateDecodingStrategy = .iso8601 |
| 81 | decoder.keyDecodingStrategy = .convertFromSnakeCase |
| 82 | return try decoder.decode(T.self, from: data) |
| 83 | } |
| 84 | ``` |
| 85 | |
| 86 | ### Downloads and Uploads |
| 87 | |
| 88 | Use `download(for:)` for large files -- it streams to disk instead of |
| 89 | loading the entire payload into memory. |
| 90 | |
| 91 | ```swift |
| 92 | // Download to a temporary file |
| 93 | let (localURL, response) = try await URLSession.shared.download(for: request) |
| 94 | |
| 95 | // Move or copy the returned temporary file promptly. |
| 96 | let destination = documentsDirectory.appendingPathComponent("file.zip") |
| 97 | try FileManager.default.moveItem(at: localURL, to: destination) |
| 98 | ``` |
| 99 | |
| 100 | For delegate-based `URLSessionDownloadDelegate`, move or open the temporary |
| 101 | file before `urlSession(_:downloadTask:didFinishDownloadingTo:)` returns. |
| 102 | |
| 103 | Background sessions are delegate-driven transfer queues. Use task creation |
| 104 | APIs such as `downloadTask(with:)` and file-backed `uploadTask(with:fromFile:)`, |
| 105 | then handle `URLSessionDelegate` / task delegate callbacks. Do not use async |
| 106 | convenience APIs such as `data(for:)`, `download(for:)`, or `upload(for:)` as |
| 107 | the durable background-session pattern. |
| 108 | |
| 109 | ```swift |
| 110 | // Upload data |
| 111 | let (data, response) = try await URLSession.shared.upload(for: request, from: bodyData) |
| 112 | |
| 113 | // Upload from file |
| 114 | let (data, response) = try await URLSession.shared.upload(for: request, fromFile: fileURL) |
| 115 | ``` |
| 116 | |
| 117 | ### Streaming with AsyncBytes |
| 118 | |
| 119 | Use `bytes(for:)` for streaming responses, progress tracking, or |
| 120 | line-delimited data (e.g., server-sent events). |
| 121 | |
| 122 | ```swift |
| 123 | let (bytes, response) = try await URLSession.shared.bytes(for: request) |
| 124 | |
| 125 | for try await line in bytes.lines { |
| 126 | // Process each line as it arrives (e.g., SSE stream) |
| 127 | handleEvent(line) |
| 128 | } |
| 129 | ``` |
| 130 | |
| 131 | ## API Client Architecture |
| 132 | |
| 133 | ### Protocol-Based Client |
| 134 | |
| 135 | Define a protocol for testability |