ios NSURLResponse - 如何获取状态代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25431042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:59:05 来源:igfitidea点击:
NSURLResponse - How to get status code?
提问by inorganik
I have a simple NSURLRequest:
我有一个简单的 NSURLRequest:
[NSURLConnection sendAsynchronousRequest:myRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// do stuff with response if status is 200
}];
How do I get the status code to make sure the request was ok?
如何获取状态代码以确保请求正常?
回答by inorganik
Cast an instance of NSHTTPURLResponse
from the response and use its statusCode
method.
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
}];
回答by Bjarte
In Swift with iOS 9 you can do it this way:
在带有 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()
}
回答by Haroldo Gondim
Swift 4
斯威夫特 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()