13

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

2 Answers 2

43

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;
}
3
  • 1
    it is not the same response, this is response from server, response inside sessionDataTask is response from http (headers and so on) Dec 14, 2015 at 16:18
  • Thanks for the answer! Better call isKindOfClass on sessionDataTask.response. Only if YES cast and get statusCode. Jul 4, 2017 at 18:34
  • @meaning-matters, Sorry not quite sure what you mean, could you suggest an edit?
    – Ollie
    Jul 5, 2017 at 15:16
1

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.