简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM