【问题标题】:NSURLResponse - How to get status code?NSURLResponse - 如何获取状态码?
【发布时间】:2014-08-21 16:11:27
【问题描述】:

我有一个简单的 NSURLRequest:

[NSURLConnection sendAsynchronousRequest:myRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    // do stuff with response if status is 200
}];

如何获取状态码以确保请求正常?

【问题讨论】:

  • 我不确定,但你不需要检查 200 状态码。如果您的服务器发送另一个状态码,您将在 completionHandler 中得到一个错误对象并可以检查。
  • 还有其他状态代码表示不是错误的结果,例如重定向或未找到,可能还有其他我无法想到的其他状态代码(与身份验证相关的等)

标签: ios objective-c


【解决方案1】:

从响应中投射NSHTTPURLResponse 的实例并使用其statusCode 方法。

[NSURLConnection sendAsynchronousRequest:myRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    NSLog(@"response status code: %ld", (long)[httpResponse statusCode]);
    // do stuff
}];

【讨论】:

  • 我们能否确定这确实是NSHTTPURLResponse 的一个实例,还是值得与isKindOfClass:respondsToSelector: 进行检查?
  • @TimArnold 是的,它是 NSHTTPURLResponse 的一个实例,所以它具有该类的所有属性和方法。
  • 正如docs 所说:Whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the NSHTTPURLResponse class.
【解决方案2】:

在带有 iOS 9 的 Swift 中,您可以这样做:

if let url = NSURL(string: requestUrl) {
    let request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 300)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)

    let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        if let httpResponse = response as? NSHTTPURLResponse {
            print("Status code: (\(httpResponse.statusCode))")

            // do stuff.
        }
    })

    task.resume()
}

【讨论】:

  • 用objective-c标记的问题。
  • objective-c 的方法和顺序是一样的。
【解决方案3】:

斯威夫特 4

let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in

    if let httpResponse = response as? HTTPURLResponse {
        print("Status Code: \(httpResponse.statusCode)")
    }

})

task.resume()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多