HTTPURLResponse: Reading the Server's Reply

Think of HTTPURLResponse as the envelope for a server's reply. It holds metadata like the status code (200 OK, 404 Not Found) and headers. You'll handle this after every URLSession call to check if your request succeeded.
WHY IT EXISTS: A raw network response is just a stream of bytes. To make sense of it in the context of the web's primary protocol, HTTP, we need a structured way to access metadata like success/failure codes, content type, and caching policies. HTTPURLResponse provides this structure.
THE MENTAL MODEL: HTTPURLResponse is like the envelope and customs declaration for a package you receive. The package's contents are the Data, but the envelope tells you who sent it (the URL), whether it was successfully delivered (the status code), and other handling instructions (the headers). You always check the envelope before opening the package.
HOW IT WORKS: When you make a network request using URLSession, the completion handler gives you (Data?, URLResponse?, Error?). The URLResponse object is generic. You typically need to safely cast it to its more specific subclass, HTTPURLResponse, to access HTTP-specific properties. The most important are statusCode, an integer representing the HTTP status, and allHeaderFields, a dictionary containing the response headers.
WHEN TO USE IT: Use it after every URLSession task that communicates with an HTTP or HTTPS endpoint. Your first step in the completion handler, after checking for a fundamental Error, should be to cast the URLResponse to HTTPURLResponse and inspect the statusCode. A status code in the 200-299 range generally indicates success.
WHEN NOT TO USE IT: You won't get an HTTPURLResponse if the underlying protocol isn't HTTP(S). For example, if you are accessing a local file URL (file://) or an FTP server, you will receive a plain URLResponse, and attempting to cast it to HTTPURLResponse will result in nil.
ONE CANONICAL EXAMPLE: A common pattern is to use a guard statement to safely unwrap and cast the response, then check the status code. guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { // Handle error and return }. This single line validates that you received an HTTP response and that the status code indicates success. Only then would you proceed to decode the Data.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.