Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get http response status code of URLSession.shared.dataTask

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?

like image 834
J.Doe Avatar asked Oct 30 '22 02:10

J.Doe


1 Answers

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.

like image 66
Tom E Avatar answered Nov 16 '22 12:11

Tom E