I request a web page with this code
URLSession.shared.dataTask(with: NSURL(string: url)! as URL, completionHandler: { (data, response, error) -> Void in
if error == nil && data != nil {
// No error
}else{
// Error
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.statusCode)
}
}
I am trying to get the error code when requesting a page by casting the response to HTTPURLResponse
but the cast dose not work and the print is not executed. Do you know how can I get the code?
Your if let httpResponse
code runs only in the else
branch of the error checking if
statement. You might also want to check the response in such cases when no error has occurred.
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