Tengo una NSURLRequest simple:
[NSURLConnection sendAsynchronousRequest:myRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// do stuff with response if status is 200
}];
¿Cómo obtengo el código de estado para asegurarme de que la solicitud fue correcta?
ios
objective-c
inorgánico
fuente
fuente
Respuestas:
Lanza una instancia de
NSHTTPURLResponse
de la respuesta y usa sustatusCode
método.[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 }];
fuente
NSHTTPURLResponse
, o vale la pena verificar conisKindOfClass:
orespondsToSelector:
?Whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the NSHTTPURLResponse class.
En Swift con iOS 9 puedes hacerlo de esta manera:
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() }
fuente
Rápido 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()
fuente