获取URLSession.shared.dataTask的http响应状态码

问题描述 投票:0回答:2

我请求使用此代码的网页

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)
 }
}

我试图通过将响应强制转换为

HTTPURLResponse
来请求页面时获取错误代码,但强制转换不起作用并且打印未执行。你知道我怎样才能得到代码吗?

ios swift nsurlsession
2个回答
2
投票

您的

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


0
投票

我需要一个解决方案,这是我通过大量测试得到的代码:

func getChuckNorrisDat(){           
     var data: Data? = nil
     var response: HTTPURLResponse? = nil
            
     do {
           (data, response) = try await (URLSession.shared.data(from: URL(string:"https://api.chucknorris.io/jokes/random-")!) as? (Data, HTTPURLResponse))!
         // catches errors in response from web api -- so web api has been
         // successfully contacted but a "normal" status error occurs
         // Other bad errors throw exceptions which is caught below
         // bad URL like string:"https://api.chucknorris.io/jokes/random-"
      // real URL is https://api.chucknorris.io/jokes/random (no dash at end)
         // will cause this error (404)
         switch response?.statusCode{
             case _ where response!.statusCode < 200 || response!.statusCode >= 300:
             return "Couldn't carry on.  Bad status code from API \(response?.statusCode)"
             default:
                print("Success!")
            }
        }
        catch{
                // catches errors when the URL is not well formed
                // bad URL like the following causes this exception:
                // (notice the x in the protocol portion of URL
                // string:"httpxs://api.chucknorris.io/jokes/random"
                print("!! What ERROR? \(error.localizedDescription)")
                return "\(error.localizedDescription)"
            }
}

我做的第一件事是设置两个变量

data
response
来保存调用
data()
方法的返回值。

请注意,我们必须将

response
转换为
HTTPURLResponse
,这样我们就可以使用
.statusCode
属性。

其余部分在代码示例中进行了解释。
这很好用。

© www.soinside.com 2019 - 2024. All rights reserved.