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)
}
}
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With