Reading data from response header of NSURLConnection
Asked Answered
V

3

32

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

Valorize answered 8/6, 2011 at 0:34 Comment(0)
T
78

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
Tonality answered 8/6, 2011 at 0:38 Comment(0)
C
4

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]);
    }
Choli answered 24/1, 2017 at 8:26 Comment(0)
C
0

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..
Cadmarr answered 22/5 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.