How To Check Response.statusCode in sendSynchronousRequest on Swift
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
If you are using the old synchronous request API in Swift, the statusCode is available on the returned response object after you cast it to HTTPURLResponse. The broader point, though, is that synchronous requests are legacy behavior and should be reserved for controlled contexts such as command-line tools or background-only code, not UI work.
Cast the Response to HTTPURLResponse
The HTTP status code is not available on the generic URLResponse type. You need to cast it to HTTPURLResponse before reading statusCode.
A typical Foundation example looks like this:
The important line is the cast:
Without that cast, Swift only sees a generic response object and statusCode is not available.
Understand the Difference Between Network Failure and HTTP Failure
An HTTP 404 or 500 is still a valid HTTP response, so error may be nil even when the request failed from the application's perspective. That means you need to check both the transport error and the status code.
A practical pattern is:
This keeps network-layer problems separate from application-layer HTTP results.
Why This API Is Usually the Wrong Choice Today
NSURLConnection.sendSynchronousRequest blocks the current thread until the request finishes. On the main thread, that can freeze a macOS or iOS interface. That is why modern Swift networking generally uses URLSession with async callbacks or async-await.
The modern equivalent is much cleaner:
So if you are only asking how to read the status code, the answer is the cast. If you are designing new code, the real answer is to move away from synchronous requests entirely.
A Small Helper Function
If you are maintaining legacy code and want the status code logic in one place, wrap it in a helper.
That keeps the cast and error handling together and makes the rest of the code clearer.
Common Pitfalls
- Trying to read
statusCodefromURLResponsedirectly does not work. You must cast toHTTPURLResponse. - Assuming
error == nilmeans the request succeeded is incorrect because HTTP404and500still return valid responses. - Running synchronous requests on the main thread can freeze the user interface.
- Ignoring the response body makes debugging harder when the server returns useful error details along with the status code.
- Writing new networking code around
sendSynchronousRequestis a maintenance problem because the API is legacy and modern Swift usesURLSessioninstead.
Summary
- Cast the returned response to
HTTPURLResponseto accessstatusCode. - Check both the transport error and the HTTP status code because they represent different failure modes.
- Use synchronous requests only in limited non-UI scenarios.
- Prefer
URLSessionfor modern Swift code. - If you must keep the legacy API, wrap the cast and status handling in a small helper function.

