How do I detect and handle 401/403/500 status codes in Swift?

When working with APIs in Swift, handling HTTP response status codes such as 401, 403, and 500 is essential for effective error handling. Below is an example of how to detect these status codes in Swift and respond accordingly.

import Foundation func handleResponse(response: URLResponse?, error: Error?) { guard let httpResponse = response as? HTTPURLResponse else { print("Invalid response") return } switch httpResponse.statusCode { case 200: print("Success!") case 401: print("Unauthorized access. User needs to log in.") case 403: print("Forbidden access. User does not have permission.") case 500: print("Server error. Please try again later.") default: print("Unhandled status code: \(httpResponse.statusCode)") } }

Swift HTTP status code handling error handling API response management