user3581248
user3581248

Reputation: 1014

NSURLSession data task response handling

I am currently working on implementing a networking model that communicates with a REST API through HTTP in Swift using NSURLSession class.

For preparing the request, I use this code:

    var request = URLRequest(url: requestURL) // url is "http://somethingsomething...
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = body

Now, I am sending the requests that way:

    session.dataTask(with: request) { data, response, error in
       // Parse the data, response and error
    }.resume()

My problem is that I want to check the httpStatusCode of the response in order to inform about possible errors, however, the response inside the completion block is of type URLResponse, not HTTPURLResponse. This means that I have to cast the response to the type HTTPURLResponse. So far I've thought of two ways to approach it - first is to add another error scenario which would handle the "couldn't cast to HTTPURLResponse" scenario, the other way is to simply force the cast to HTTPURLResponse. The first option seems better but it could be just adding some useless code, because maybe the cast will always succeed?

So basically, my question is - can I be sure that, if I send the requests to a HTTP server, the response will always be of HTTPURLResponse type? Or do I have to implement the code that handles a situation where the response object is of a different type or is a nil?

Also, I think it would be good to mention that in my implementation if the completion block returns error that is not nil, the flow will return before trying to cast anything.

Upvotes: 1

Views: 1166

Answers (1)

Sethmr
Sethmr

Reputation: 3074

I believe this is what you need.

session.dataTask(with: request) { data, response, error in
    // Parse the data, response and error
    if let httpResponse = response as? HTTPURLResponse {
        //here it is
        print(httpResponse.statusCode)
    }
}.resume()

I have never had the cast fail to my knowledge. I am not sure why URLResponse and HTTPURLResponse aren't merged into one class, but HTTPURLResponse is a subclass that the response always can be cast to as far as my knowledge goes.

Upvotes: 0

Related Questions