Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 146 ยท Standard Library and Foundation

Networking with URLSession

Learn URLSession in Swift: URLRequest, async data(for:), status codes, JSON decoding, errors, cancellation and testing with a URLProtocol stub that runs here.

Almost every app talks to a server sooner or later: it loads a profile, posts a form, downloads an image. In Swift the workhorse for that job is URLSession, a class from Foundation that sends HTTP requests and gives you back bytes and a response. Since Swift 5.5 it has async methods, so a network call reads like any other function call: let (data, response) = try await session.data(from: url).

This lesson teaches the whole shape of a network call: the request value, the response, status codes, decoding, errors, cancellation and, most importantly, how to test network code without a network. That last part matters here, because the sandbox that runs the examples on this page has no internet access. Everything you can run below works offline, using a stub that plays the part of the server. The same code works against a real server by removing one line.

On Apple platforms URLSession is part of Foundation. On Linux and Windows it lives in a separate module, FoundationNetworking, so portable code writes #if canImport(FoundationNetworking) followed by import FoundationNetworking. The examples below do exactly that. Apple's own frameworks for sockets and streams (Network.framework, NWConnection) are not available on Linux and are not covered here.

The pieces: URL, URLRequest, URLResponse

A network call has three value types worth knowing before you send anything:

  • URL says where to go. See UUID, URL and URLComponents for building and escaping them safely.
  • URLRequest says how: the URL plus an HTTP method, headers, a body and a timeout.
  • URLResponse (almost always an HTTPURLResponse) says what came back: status code and headers. The body arrives separately as Data.

URLRequest is a struct, so you build it like any other value, and none of this touches the network yet:

Swift Building a request and a response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You should see POST, the URL, the header dictionary, 16 body bytes, default timeout: 60.0, then 404 Not Found and abc. Two details are worth remembering. Header lookup on a response is case-insensitive (x-request-id found X-Request-Id), as HTTP requires. And httpMethod defaults to GET; if you set httpBody but forget the method, you send a GET with a body, which many servers ignore.

Sessions and configuration

A URLSession owns connections, cookies, caching and timeouts. Most code uses one of three kinds:

  • URLSession.shared: a ready-made session with default settings. Fine for simple calls.
  • A session you create from a URLSessionConfiguration: .default (disk cache and cookies), .ephemeral (everything in memory, nothing saved), or .background (Apple platforms only; transfers continue while the app is suspended).
  • Inside tests, a session whose configuration lists a URLProtocol stub, as you will see shortly.

The configuration is where timeouts, extra headers and connection limits go. It is copied when the session is created, so change it first:

Swift
// Read-only example: configuring a session for a real app.
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 15        // seconds of silence before failing
config.httpAdditionalHeaders = ["Accept": "application/json"]
config.waitsForConnectivity = true           // wait instead of failing at once when offline
let session = URLSession(configuration: config)

Create one session and reuse it. A new session per request throws away connection reuse and is slower for your users and heavier on the server.

Making a request with async/await

The two methods you will use constantly:

Swift
// Read-only example: this needs a real network.
let (data, response) = try await URLSession.shared.data(from: url)       // simple GET
let (data2, response2) = try await URLSession.shared.data(for: request)  // full control

Both return a tuple of Data and URLResponse and throw if the request could not be completed at all: no connection, timeout, bad certificate, cancelled. If you want a file instead of memory, download(from:) writes to a temporary file, and upload(for:from:) sends a body without loading it all into a request.

A 404 or 500 is not a thrown error. data(for:) only throws when no HTTP response could be obtained. When the server answers "not found", the call succeeds, and you must look at statusCode yourself. Forgetting this is the most common URLSession bug: the app then tries to decode an error page as if it were your JSON.

Checking the response

The honest pattern has three steps: confirm it is an HTTP response, check the status range, then decode. The next example wraps those steps in one generic function. To make it runnable without a server, the session is given a stub (explained in the next section), which answers a few fixed paths.

Swift A generic, checked JSON request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is four lines: /user decodes to User(name: "Ada", age: 36), /missing fails with badStatus(404), /broken with badStatus(500), and /garbage with a decoding error whose text says the data was not valid JSON. Notice that three different failures are now three different, nameable cases. Your UI can show "please log in" for 401, "try again later" for 500 and "update the app" for a decoding failure. The error types come from Custom errors, and the decoding step from Working with JSON.

Stubbing the network with URLProtocol

How did that code run without a server? A URLProtocol is the class URLSession hands each request to, to do the actual loading. Built-in subclasses speak HTTP and HTTPS. If you list your own subclass in protocolClasses, it gets the first chance to claim every request, and it can answer with whatever bytes you choose. Your production code does not change at all, which is the whole point.

A stub has four jobs:

  1. canInit(with:): return true for requests it wants to handle.
  2. canonicalRequest(for:): normally return the request unchanged.
  3. startLoading(): produce the response by calling the three client methods in order: didReceive (the response), didLoad (the body, possibly several times), urlProtocolDidFinishLoading. To simulate a failure call client?.urlProtocol(self, didFailWithError:) instead.
  4. stopLoading(): clean up if the request is cancelled.

Make the stub decide from the request (the path or a header), not from shared mutable state. Swift 6 rejects a static mutable "handler" property in a URLProtocol subclass, because loading happens on other threads. If a test needs different answers, give each test its own path.

Cancellation and timeouts

Because data(for:) is async, it takes part in cooperative cancellation. If the surrounding Task is cancelled, the request is stopped and the call throws a URLError whose code is .cancelled. A slow-loading screen that the user leaves should cancel its task, and the connection is torn down for you. A stub that never answers lets us watch this happen:

Swift Cancelling a request in flight

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see stopLoading called (the protocol was told to stop) and then cancelled: true code: -999. -999 is NSURLErrorCancelled, the number every Apple developer eventually recognizes in a log. When catching network errors, treat .cancelled as "not an error to show the user". Other common codes: .timedOut (-1001), .notConnectedToInternet (-1009), .cannotFindHost (-1003), .secureConnectionFailed (-1200).

Designing network code you can test

Stubbing URLProtocol tests the real URLSession path, but for most unit tests there is a lighter and more flexible tool: put a small protocol in front of the network and pass in a fake. The calling code then depends on an abstraction you control:

Swift A fake transport behind a protocol

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

WeatherClient never mentions URLSession; it only knows Transport. In the app you would write WeatherClient(transport: LiveTransport(session: .shared)). In tests you pass the fake and check URLs, query strings and failure handling instantly and deterministically. The Sendable requirement on Transport is part of Swift 6: the client may be used from several tasks, so whatever it holds must be safe to share. See Sendable. The query string was built with URLComponents, which escapes Oslo and anything stranger correctly; never glue user input into a URL with string interpolation.

What is under the hood

HTTP is just text over a TCP connection. Foundation hides that, but seeing it once makes error messages and proxies less mysterious. The sandbox forbids outside connections but allows loopback (127.0.0.1, your own machine), so we can run a tiny server and client inside one program using the C socket functions that Swift can call directly (the technique is covered in Interoperating with C). This is a demonstration of the protocol, not a recommendation: real servers should use SwiftNIO or Vapor (see Swift on the server).

Swift HTTP by hand over loopback sockets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The server sees one line, GET /hello HTTP/1.1, and the client gets back a status line, headers, an empty line and the body, shown joined with |. That is all URLSession writes and reads for you, plus TLS, redirects, caching, compression, cookies, HTTP/2 and connection pooling.

Real transfers do not work in this sandbox. If you point URLSession.shared at even a loopback HTTP server here, the program stops with Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=libcurl.Easy Code=48 coming from inside FoundationNetworking. On Linux, URLSession uses libcurl and fails while setting up a certificate bundle the sandbox does not have. file:// URLs are not supported by URLSession on Linux at all (error -1002, "unsupported URL"; use Data(contentsOf:) or FileManager instead). On a normal Linux machine or on your Mac, real requests work as described. This is why the lesson uses stubs.

Practical advice

  • Always check the status code, then decode. A decode error after a bad status hides the real cause.
  • Use one session, give it a sensible timeoutIntervalForRequest, and handle URLError separately from your own errors.
  • Decode on the caller's terms: set JSONDecoder.keyDecodingStrategy = .convertFromSnakeCase and dateDecodingStrategy = .iso8601 once, not at every call site.
  • Retry only idempotent requests (GET, PUT, DELETE), with exponential backoff and a limit. A retried POST can create the same order twice.
  • Never disable certificate checks to "make it work". Fix the certificate instead.
  • On Apple platforms add async delegate methods for authentication challenges and progress; Combine publishers and URLSession.dataTaskPublisher exist but new code should prefer async/await. Both are Apple-only and not runnable here.
  • Do UI updates on the main actor after the call returns; see Async/await and Actors.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A server answers a request with status 404. What does try await session.data(for: request) do?

    URLSession only throws when no HTTP response could be obtained (no connection, timeout, cancellation). Any answer from the server, even 404 or 500, is a successful transfer, so check the status code before decoding.
  2. 2. Which URLSessionConfiguration keeps cookies and cache purely in memory?

    .ephemeral stores nothing on disk, like a private browsing window. .default uses disk caches and cookies, .background is for transfers that continue when the app is suspended (Apple platforms), and shared is a session, not a configuration.
  3. 3. What is the purpose of listing a URLProtocol subclass in protocolClasses?

    URLSession gives each request to the first protocol class that says canInit. A stub can then return fixed bytes, so the real URLSession code runs without any server.
  4. 4. What error code do you get when a task is cancelled while a request is in flight?

    Cancelling the Task cancels the transfer, and the call throws a URLError with code .cancelled (-999). Do not show that to the user as a failure.
  5. 5. On Linux, which module must you import to use URLSession?

    swift-corelibs-foundation splits the networking types into FoundationNetworking. Portable code imports it behind #if canImport(FoundationNetworking).

Summary

  • URLRequest describes the call (URL, method, headers, body, timeout); URLSession sends it; the result is Data plus an HTTPURLResponse.
  • try await session.data(for:) throws only when no response was obtained. Always check statusCode, then decode.
  • Reuse one configured session; .ephemeral keeps everything in memory.
  • Cancelling the Task cancels the request and throws URLError code .cancelled (-999).
  • Test network code with a URLProtocol stub in protocolClasses, or put a small Transport protocol in front of the session and pass a fake.
  • On Linux import FoundationNetworking; in this sandbox real transfers are unavailable, so the examples use stubs and loopback sockets.

Next: Printing and Debugging