NSURLResponse
HTTP Status Code
iOS Development
Swift
Networking

NSURLResponse - How to get status code?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

NSURLResponse is a foundational class in the Foundation framework of Apple's development environment. It provides information about the response that an application receives from an HTTP request. However, if you need to retrieve specific details like the HTTP status code, NSURLResponse alone doesn't suffice. Instead, you should use its subclass, `NSHTTPURLResponse`.

`NSHTTPURLResponse` is designed to handle HTTP-specific details, including the all-important status code. This article delves into the technicalities of `NSHTTPURLResponse` and demonstrates how to effectively extract the status code from an HTTP response.

Understanding `NSHTTPURLResponse`

What is NSHTTPURLResponse?

`NSHTTPURLResponse` inherits from `NSURLResponse` and is tailored to encompass additional HTTP-specific information contained within an HTTP response. It provides access to valuable metadata such as HTTP headers, status codes, and more. Here's a brief overview of its main functionalities:

  • Status Code: The HTTP status code of the response.
  • Headers: A dictionary containing the headers that come with the response.
  • URL: The URL associated with the response.

Why is the Status Code Important?

The HTTP status code is crucial for determining the result of an HTTP request. It informs the developer about the success or failure of the request and provides valuable context on what action to take next. Status codes are standardized, allowing applications to respond correctly no matter the server configuration.

Retrieving the Status Code

To extract the status code from an `NSHTTPURLResponse`, you must ensure that your response object is indeed an instance of this subclass. Here is a step-by-step guide:

Example Code in Swift

  • 200 OK: The request has succeeded.
  • 301 Moved Permanently: The requested resource has been assigned a new permanent URI.
  • 400 Bad Request: The server cannot process the request due to a client error.
  • 401 Unauthorized: Authentication is required and has failed or not been provided.
  • 404 Not Found: The resource could not be found.
  • 500 Internal Server Error: A generic server error message.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.