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.
Interview question
After a URLSession task completes, what is the correct logical flow for processing the (Data?, URLResponse?, Error?) tuple?
- a.Process Data first, then check HTTPURLResponse.statusCode, and finally check for Error.
- b.Cast URLResponse to HTTPURLResponse to inspect statusCode, then check for Error, then process Data.
- c.Check for Error, then immediately process Data, as HTTPURLResponse is only for content type validation.
- d.Check for Error, then cast URLResponse to HTTPURLResponse to inspect statusCode, then process Data.Correct
Why? this is the answer
The card states that after checking for a fundamental Error, the next step should be to cast the URLResponse to HTTPURLResponse and inspect the statusCode, and only then proceed to decode the Data. Option C is incorrect because HTTPURLResponse is crucial for determining the success or failure of the HTTP request via its status code, not just for content type.
Just read this? Test yourself on what you have been reading.
Read the original → developer.apple.com
- #ios
- #swift
- #networking
- #urlsession
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on ios — each one lists the topics its interview covers.
See open roles