iOS Networking
Build and review Apple-platform networking using URLSession with native async/await, structured concurrency, and Network.framework. Targets Swift 6.4 / iOS 26+.
Contents
Core Principles
- Prefer native async/await: Use
URLSession.shared.data(for:), download(for:), and bytes(for:) for all foreground network operations.
- Never swallow HTTP errors:
URLSession only throws for transport-level failures (offline, DNS, timeout). It does not throw on 4xx or 5xx responses. Always validate (200..<300).contains(httpResponse.statusCode).
- Keep retry policies bounded: Limit retries with exponential backoff and jitter. Only retry idempotent operations (GET, PUT, DELETE); never loop token refresh indefinitely.
- Isolate shared state: Isolate token storage, refresh locks, and cookie management inside actors or serial synchronization queues.
Status Code Validation and Error Contract
let (data, response) = try await session.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw NetworkError.invalidResponse
}
guard (200..<300).contains(httpResponse.statusCode) else {
throw NetworkError.httpError(statusCode: httpResponse.statusCode, data: data)
}
Differentiate error categories: transport errors (URLError), decoding errors (DecodingError), client errors (4xx), server errors (5xx), and cancellation (CancellationError).
Foreground vs Background Transfers
| Transfer Mode |
API Pattern |
Session Configuration |
Suspension Behavior |
| Foreground Data |
try await session.data(for:) |
.default or .ephemeral |
Cancelled on app suspension |
| Foreground Download |
try await session.download(for:) |
.default |
Pauses/cancels on suspension |
| Background Transfer |
session.downloadTask(with:) with delegate |
URLSessionConfiguration.background(withIdentifier:) |
Managed out-of-process; relaunches app on finish |
| WebSocket |
session.webSocketTask(with:) |
.default |
Reconnection required on resume |
Route by Task
- For building reusable API clients, request encoders, authentication headers, and actors, read API Client and Request Building and Lightweight Clients.
- For resilient retries, certificate pinning, TLS security, and byte streaming, read Resilience, Security, and Streaming.
- For large file uploads, resume data, and progress tracking, read Uploads and Downloads and File Storage Patterns.
- For background transfers and app relaunch handlers, read Background Transfers. For real-time WebSockets, read WebSocket Networking.
- For cursor/offset pagination, AsyncSequence streams, and URLProtocol unit testing, read Pagination and URLProtocol Testing.
- For low-level TCP/UDP sockets, path monitoring, and cellular constraints with
NWPathMonitor, read Network Framework.
Common Mistakes
- Assuming
URLSession.data(for:) throws on HTTP 404 or 500 responses instead of inspecting statusCode.
- Using async/await convenience overloads on background
URLSessionConfiguration, which requires delegate callbacks.
- Retrying non-idempotent POST requests automatically after a network timeout.
- Leaking
NWPathMonitor instances or starting monitoring without setting a dispatch queue.
- Moving downloaded files after returning from
urlSession(_:downloadTask:didFinishDownloadingTo:) (file is deleted upon return).
Review Checklist
References
- API client and request building
- Lightweight clients
- Resilience, security, and streaming
- Uploads and downloads
- File storage patterns
- Background transfers
- WebSocket networking
- Pagination and URLProtocol testing
- Network.framework and NWPathMonitor
- URLSession documentation
- URLRequest documentation
1---2name: ios-networking3description: "Builds or reviews Apple-platform networking with URLSession, async/await, and structured concurrency. Use for REST clients, uploads/downloads, WebSockets, pagination, retries, middleware, caching, background transfers, reachability, request errors, or network data loading."4metadata:5 source: https://skillmd.com/skills/thiennc-tesoglobal/ios-networking6---78# iOS Networking910Build and review Apple-platform networking using `URLSession` with native async/await, structured concurrency, and `Network.framework`. Targets Swift 6.4 / iOS 26+.1112## Contents1314- [Core Principles](#core-principles)15- [Status Code Validation and Error Contract](#status-code-validation-and-error-contract)16- [Foreground vs Background Transfers](#foreground-vs-background-transfers)17- [Route by Task](#route-by-task)18- [Common Mistakes](#common-mistakes)19- [Review Checklist](#review-checklist)20- [References](#references)2122## Core Principles23241. **Prefer native async/await**: Use `URLSession.shared.data(for:)`, `download(for:)`, and `bytes(for:)` for all foreground network operations.252. **Never swallow HTTP errors**: `URLSession` only throws for transport-level failures (offline, DNS, timeout). It does **not** throw on 4xx or 5xx responses. Always validate `(200..<300).contains(httpResponse.statusCode)`.263. **Keep retry policies bounded**: Limit retries with exponential backoff and jitter. Only retry idempotent operations (GET, PUT, DELETE); never loop token refresh indefinitely.274. **Isolate shared state**: Isolate token storage, refresh locks, and cookie management inside actors or serial synchronization queues.2829## Status Code Validation and Error Contract3031```swift32let (data, response) = try await session.data(for: request)3334guard let httpResponse = response as? HTTPURLResponse else {35 throw NetworkError.invalidResponse36}3738guard (200..<300).contains(httpResponse.statusCode) else {39 throw NetworkError.httpError(statusCode: httpResponse.statusCode, data: data)40}41```4243Differentiate error categories: transport errors (`URLError`), decoding errors (`DecodingError`), client errors (4xx), server errors (5xx), and cancellation (`CancellationError`).4445## Foreground vs Background Transfers4647| Transfer Mode | API Pattern | Session Configuration | Suspension Behavior |48|---|---|---|---|49| Foreground Data | `try await session.data(for:)` | `.default` or `.ephemeral` | Cancelled on app suspension |50| Foreground Download | `try await session.download(for:)` | `.default` | Pauses/cancels on suspension |51| Background Transfer | `session.downloadTask(with:)` with delegate | `URLSessionConfiguration.background(withIdentifier:)` | Managed out-of-process; relaunches app on finish |52| WebSocket | `session.webSocketTask(with:)` | `.default` | Reconnection required on resume |5354## Route by Task5556- For building reusable API clients, request encoders, authentication headers, and actors, read [API Client and Request Building](references/api-client-and-request-building.md) and [Lightweight Clients](references/lightweight-clients.md).57- For resilient retries, certificate pinning, TLS security, and byte streaming, read [Resilience, Security, and Streaming](references/resilience-security-and-streaming.md).58- For large file uploads, resume data, and progress tracking, read [Uploads and Downloads](references/uploads-and-downloads.md) and [File Storage Patterns](references/file-storage-patterns.md).59- For background transfers and app relaunch handlers, read [Background Transfers](references/background-transfers.md). For real-time WebSockets, read [WebSocket Networking](references/websocket-networking.md).60- For cursor/offset pagination, AsyncSequence streams, and URLProtocol unit testing, read [Pagination and URLProtocol Testing](references/pagination-and-urlprotocol-testing.md).61- For low-level TCP/UDP sockets, path monitoring, and cellular constraints with `NWPathMonitor`, read [Network Framework](references/network-framework.md).6263## Common Mistakes6465- Assuming `URLSession.data(for:)` throws on HTTP 404 or 500 responses instead of inspecting `statusCode`.66- Using async/await convenience overloads on background `URLSessionConfiguration`, which requires delegate callbacks.67- Retrying non-idempotent POST requests automatically after a network timeout.68- Leaking `NWPathMonitor` instances or starting monitoring without setting a dispatch queue.69- Moving downloaded files after returning from `urlSession(_:downloadTask:didFinishDownloadingTo:)` (file is deleted upon return).7071## Review Checklist7273- [ ] HTTP status code explicitly validated before decoding payload74- [ ] Transport errors separated from server-returned error payloads75- [ ] Safe retry policy with jitter applied only to idempotent requests76- [ ] Auth token refresh uses actor isolation to avoid redundant refresh calls77- [ ] Background sessions configure delegate and move temporary files synchronously78- [ ] URLProtocol tests verify 2xx, 4xx, 5xx, timeout, and cancellation states79- [ ] App Transport Security (ATS) exceptions avoided unless strictly necessary8081## References8283- [API client and request building](references/api-client-and-request-building.md)84- [Lightweight clients](references/lightweight-clients.md)85- [Resilience, security, and streaming](references/resilience-security-and-streaming.md)86- [Uploads and downloads](references/uploads-and-downloads.md)87- [File storage patterns](references/file-storage-patterns.md)88- [Background transfers](references/background-transfers.md)89- [WebSocket networking](references/websocket-networking.md)90- [Pagination and URLProtocol testing](references/pagination-and-urlprotocol-testing.md)91- [Network.framework and NWPathMonitor](references/network-framework.md)92- [URLSession documentation](https://sosumi.ai/documentation/foundation/urlsession)93- [URLRequest documentation](https://sosumi.ai/documentation/foundation/urlrequest)