Reputation: 38162
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
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
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
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