NSURLResponse-如何获取状态码?


85

我有一个简单的NSURLRequest:

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

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


我不确定,但您不必检查200状态代码。如果您的服务器发送了另一个状态代码,则您将在completionHandler中获得一个错误对象并可以进行检查。
Matz

5
还有其他状态代码代表的结果不是错误,例如重定向或未找到结果,还有其他一些我无法想到的(与身份验证相关的信息)
inorganik,

Answers:


211

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
}];

1
我们是否可以确定这确实是的实例NSHTTPURLResponse,还是值得与isKindOfClass:或检查respondsToSelector:
蒂姆·阿诺德

@TimArnold是的,它是NSHTTPURLResponse的一个实例,因此它具有该类的所有属性和方法。
inorganik

14
正如文档所说:Whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the NSHTTPURLResponse class.
Pixel Elephant 2015年

30

在带有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标记的问题。
trojanfoe

5
目标c的方法和顺序相同。
比耶特(Bjarte)

11

斯威夫特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()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.