32

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

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.. 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.