Abhinav
Abhinav

Reputation: 38162

Reading data from response header of NSURLConnection

How can I read the data from the header sent by in the server response. I am using NSURLConnection to send the request.

Upvotes: 32

Views: 20644

Answers (3)

F.A. Botic
F.A. Botic

Reputation: 111

In order to expand the accepted answer from Mr. John, i'll add a few more lines of code for better understanding of how to read each individual header:

        //NSURLResponse
        NSHTTPURLResponse *httpResponse;
        //Store all headers from the response into NSDictionary
        NSDictionary* headers = [(NSHTTPURLResponse *)httpResponse allHeaderFields];
        //The value of the header we are searching for
        NSString *redirectLocation;
        //Search all headers
        for (NSString *header in headers) {
            //Define the header name you are searching for, in this example header name is "Location"
            if([header isEqualToString:@"Location"]){
                //get value from NSDictionary by key
                redirectLocation = headers[header];
                break;
            }
        }
        //..Do whatever is required with the value from the header stored in instance variable..

Upvotes: 0

John Calsbeek
John Calsbeek

Reputation: 36537

If the URL is an HTTP URL, then the NSURLResponse that you receive in your connection's delegate's -connection:didReceiveResponse: method (or via another method) will be an NSHTTPURLResponse, which has an -allHeaderFields method that lets you access the headers.

NSURLResponse* response = // the response, from somewhere
NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields];
// now query `headers` for the header you want

Upvotes: 78

Ali
Ali

Reputation: 514

In my case

    NSHTTPURLResponse *response = ((NSHTTPURLResponse *)[task response]);
    NSDictionary *headers = [response allHeaderFields];

Good Approach

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)[task response];
    if ([httpResponse respondsToSelector:@selector(allHeaderFields)]) {
         NSDictionary *dictionary = [httpResponse allHeaderFields];
         NSLog(@"%@", [dictionary description]);
    }

Upvotes: 4

Related Questions