Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use HTTPURLResponse in place of URLResponse

Tags:

http

swift3

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)

        }

    }
like image 452
Ronald Aja Avatar asked Sep 16 '16 12:09

Ronald Aja


1 Answers

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...
    }
like image 70
OOPer Avatar answered Nov 07 '22 19:11

OOPer