NSURLResponse - Durum kodu nasıl alınır?


86

Basit bir NSURL İsteğim var:

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

İsteğin tamam olduğundan emin olmak için durum kodunu nasıl alırım?


Emin değilim, ama 200 durum kodunu kontrol etmenize gerek yok. Sunucunuz başka bir durum kodu gönderirse, completeHandler'da bir hata nesnesi alırsınız ve kontrol edebilirsiniz.
Matz

5
Yönlendirmeler veya bulunmayanlar gibi hata olmayan sonuçları temsil eden ve muhtemelen aklıma gelmeyen başkalarını (kimlik doğrulama ile ilgili vb.) Temsil eden başka durum kodları da var
inorganik

Yanıtlar:


212

Yanıttan bir örnek NSHTTPURLResponseatın ve statusCodeyöntemini kullanın .

[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
Emin bunun gerçekten bir örneği olacak olabilir NSHTTPURLResponse, ya da birlikte değer denetimi olduğunu isKindOfClass:veya respondsToSelector:?
Tim Arnold

@TimArnold evet, bu bir NSHTTPURLResponse örneğidir, dolayısıyla bu sınıfın tüm özelliklerine ve yöntemlerine sahiptir.
inorganik

14
Gibi dokümanlar ki:Whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the NSHTTPURLResponse class.
Piksel Fil

30

İOS 9 ile Swift'de bunu şu şekilde yapabilirsiniz:

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

Amaç-c ile etiketlenmiş soru.
trojanfoe

5
Amaç-c için aynı yöntem ve sıra olacaktır.
Bjarte

11

Swift 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()
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.