AFNetworking 2.0 // How to read response header

M to the K picture M to the K · Dec 6, 2013 · Viewed 11.7k times · Source

I'm using the new version of AFNetworking and I can't figure out how to read the headers of the response. I'm using the AFHTTPSessionManager to perform my query, everything works well but I'm unable to find the header response field.

Here is how I proceed

self.sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
[self.sessionManager GET:urlId parameters:nil
    success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([self.delegate respondsToSelector:@selector(userIsLoadedWithInfos:)]) {
            [self.delegate userIsLoadedWithInfos: responseObject];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if ([self.delegate respondsToSelector:@selector(userLoadingFailed)]) {
            [self.delegate userLoadingFailed];
        }
    }
];

I tried to read the response attribute of task but it return an NSURLResponse which doesn't include the headers.

Does anyone now how to read the response headers with the 2.0 version?

Answer

vikingosegundo picture vikingosegundo · Dec 6, 2013

a slightly more robust code than Viruss mcs's:

if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
    NSHTTPURLResponse *r = (NSHTTPURLResponse *)task.response;
    NSLog(@"%@" ,[r allHeaderFields]);
}

returns

{
    Connection = "Keep-Alive";
    "Content-Length" = 12771;
    "Content-Type" = "application/json";
    Date = "Fri, 06 Dec 2013 10:40:48 GMT";
    "Keep-Alive" = "timeout=5";
    "Proxy-Connection" = "Keep-Alive";
    Server = "gunicorn/18.0";
}

similarly you can assure the casting is done right with [response respondsToSelector:@selector(allHeaderFields)], but you should also call that before you do the cast

if ([task.response respondsToSelector:@selector(allHeaderFields)]) {
    NSHTTPURLResponse *r = (NSHTTPURLResponse *)task.response;
    NSLog(@"%@" ,[r allHeaderFields]);
}

or no cast at all:

if ([task.response respondsToSelector:@selector(allHeaderFields)]) {
    NSLog(@"%@" ,[task.response performSelector:@selector(allHeaderFields)]);
}