12.10 · Network.framework, background sessions, delegates versus async, diagnosing and measuring
Some jobs need more than data(for:): raw connections, transfers that survive termination, challenges and metrics, and the habit of diagnosing a failure from the outside.
Mental model. Pick the lowest-level tool that fits, and know what each one gives up: URLSession gives HTTP for free; NWConnection gives you the bytes and the responsibility.
Lower-level and background
NWConnection and when you still need a session delegate.
- When do you use Network.framework (NWConnection, NWListener, NWPathMonitor) instead of URLSession, and how does a connection move through its states?
Use URLSession for anything that is HTTP: it brings caching, cookies, redirects, HTTP/2 and 3, proxies, authentication, background transfers and the system’s… - When do you still need a URLSession delegate, and how do the async APIs and per-task delegates fit?
The async methods (data(for:), download, upload, bytes) cover most calls with no delegate. You still need one, at session or task level, for things that are…
Diagnosing and measuring
Finding out why a request is slow or failing, and what the metrics tell you.
- A request fails or is slow only for some users. How do you diagnose it: what do you log, what tools do you use, and what are the usual causes?
Work from the outside in. First reproduce and classify: is it a URL or request problem (check the exact URL, headers, body; log it without secrets), a… - What does URLSessionTaskMetrics tell you about a request, and how do you use it to find where time goes?
After a task finishes the session delegate (or URLSessionTaskDelegate’s urlSession(_:task:didFinishCollecting:)) receives URLSessionTaskMetrics: the total task…
More in Networking
- 12.1 · Sessions, configurations, tasks, delegates and background transfers
- 12.2 · HTTP versions, TLS, App Transport Security and certificate pinning
- 12.3 · Pagination, caching and conditional requests, and authentication refresh
- 12.4 · WebSockets, multipart and large transfers, and network path monitoring
- 12.5 · Retries, backoff, idempotency and cancellation
- 12.6 · REST, GraphQL and gRPC, and building a client platform
- 12.7 · Image loading pipelines: download, decode, downsample, cache
- 12.8 · Building URLs, reading headers, classifying errors and timeouts
- 12.9 · Single-flight token refresh, streaming lines, multipart bodies and request signing