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.

  1. When do you use Network.framework (NWConnection, NWListener, NWPathMonitor) instead of URLSession, and how does a connection move through its states? 12.10.1 · L5
    Use URLSession for anything that is HTTP: it brings caching, cookies, redirects, HTTP/2 and 3, proxies, authentication, background transfers and the system’s…
  2. When do you still need a URLSession delegate, and how do the async APIs and per-task delegates fit? 12.10.2 · L3
    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.

  1. 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? 12.10.3 · L3
    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…
  2. What does URLSessionTaskMetrics tell you about a request, and how do you use it to find where time goes? 12.10.4 · L5
    After a task finishes the session delegate (or URLSessionTaskDelegate’s urlSession(_:task:didFinishCollecting:)) receives URLSessionTaskMetrics: the total task…

More in Networking