Ronald Aja Ronald Aja - 2 months ago 19
HTTP Question

Use HTTPURLResponse in place of URLResponse

I want to call an API and its a part of my app, but I want to make sure I get the status code of the site I am calling into (to prevent runtime errors). I can't get the status code for URLResponse, but I can get it for HTTPURLResponse. How do I use the latter in place of the former?

let requestURLString = "my_http_url"
let requestURL = URL(string: requestURLString)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let ETAreq = session.dataTask(with: requestURL!)
{

(data, response (this is the URLResponse), error) in

if error == nil
{

//switch (this is where I will put switch of status code)

}

}

Answer

Though, URLResponse and HTTPURLResponse are renamed with losing NS-prefix. They still are classes and HTTPURLResponse is a subclass of URLResponse.

HTTPURLResponse

You can use as? or as!:

    if
        error == nil,
        let httpResponse = response as? HTTPURLResponse
    {
        switch httpResponse.statusCode {
        case 200:
            //...
            break
        //...
        default:
            break
        }
    } else {
        //error case here...
    }