Safely Force Downcasting a URLResponse to an HTTPURLResponse

When URLSession.dataTask(with request: URLRequest, completionHandler:) returns a nil error, is the URLResponse response parameter guaranteed to be an HTTPURLResponse, so that it is safe to force downcast the URLResponse to an HTTPURLResponse?


This article does not force cast the URLResponse to an HTTPURLResponse when there is no error:

https://developer.apple.com/documentation/foundation/url_loading_system/fetching_website_data_into_memory


These examples do:

https://developer.apple.com/documentation/network/debugging_http_server-side_errors

https://forums.developer.apple.com/message/351326#351326


Thanks!

Accepted Reply

[Is it] safe to force downcast the

URLResponse
to an
HTTPURLResponse
?

Yes, assuming that the URL in the request has an HTTP scheme (

http
or
https
). Personally, I always force cast this. If you use a conditional cast, there’s no meaningful error handling you can apply.

These examples do

Yeah, that’d be because I wrote them both (-:

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

[Is it] safe to force downcast the

URLResponse
to an
HTTPURLResponse
?

Yes, assuming that the URL in the request has an HTTP scheme (

http
or
https
). Personally, I always force cast this. If you use a conditional cast, there’s no meaningful error handling you can apply.

These examples do

Yeah, that’d be because I wrote them both (-:

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
If there are network connectivity issues (e.g. the device is in Airplane Mode), forced downcasts seem to fail and throw an exception.

forced downcasts seem to fail and throw an exception.

That’s most likely because you got an error, whereupon the response will be nil. When dealing with URLSession response, you should always check for an error first and, if you see one, ignore response and data.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"