[ios] NSURLResponse-상태 코드를 얻는 방법?

간단한 NSURLRequest가 있습니다.

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

요청이 정상인지 확인하는 상태 코드는 어떻게 얻습니까?



답변

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


답변

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


답변

스위프트 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()


답변