获取urlsession .share . datatask的http响应状态代码

时间:2022-10-09 00:13:59

I request a web page with this code

我使用此代码请求一个web页面

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?

在请求页面时,我试图获取错误代码,方法是将响应转换为HTTPURLResponse,但转换不起作用,打印也没有执行。你知道我怎样才能拿到密码吗?

1 个解决方案

#1


1  

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.

如果让httpResponse代码只在错误检查if语句的else分支中运行。您可能还想在没有发生错误的情况下检查响应。

#1


1  

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.

如果让httpResponse代码只在错误检查if语句的else分支中运行。您可能还想在没有发生错误的情况下检查响应。