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