Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get status code from NSURLSessionDataTask?

In AFNetworking 3.0 some things was changed. Basicaly, there is no more operations, instead session data tasks. How can I get status code from NSURLSessionDataTask?

This is my block:

    GET("users/check_email", parameters: parameters, progress: nil, success: { sessionDataTask, response in

        // here I need status code of response

        }) { sessionDataTask, error in

            completionBlock(nil, NSError(sessionDataTask: sessionDataTask))
    } 
like image 669
Bartłomiej Semańczyk Avatar asked Dec 14 '15 16:12

Bartłomiej Semańczyk


2 Answers

The NSURLSessionDataTask has a response property that can be cast to a NSHTTPURLResponse to get the status code:

Swift Example:

if let urlResponse = sessionDataTask.response as? NSHTTPURLResponse {
    let status = urlResponse.statusCode
}

Objective-C Example:

NSInteger statusCode = 0;

if ([sessionDataTask.response isKindOfClass:[NSHTTPURLResponse class]]) {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)sessionDataTask.response;
    statusCode = httpResponse.statusCode;
}
like image 131
Ollie Avatar answered Nov 02 '22 02:11

Ollie


NSURLSessionDataTask has response property, which will be populated with an object of NSHTTPURLResponse class, which has statusCode property.

like image 1
bteapot Avatar answered Nov 02 '22 02:11

bteapot