Thursday, October 27, 2011

How to Handle HTTP Headers in iOS4 and iOS5

One of several minor incompatibilities between iOS4 and iOS5 is the way how HTTP headers are reported. The difference is in the capitalization and white-space handling:
iOS4: @"Myapp-Sampleheader ";
iOS5: @"MyApp-SampleHeader";
Once you figure out this is the problem, the fix is quite easy. Here is a generic routine to handle both cases at the same time:

- (void)connection:(NSURLConnection *)aConnection
  didReceiveResponse:(NSURLResponse *)aResponse
{
  NSString *myHttpHeader = @"myapp-sampleheader-10";
  NSDictionary *dict = [httpResponse allHeaderFields];
  for (NSString *key in dict)
  {
    NSString *test = [key stringByTrimmingCharactersInSet:
      [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([[test lowercaseString] isEqualToString:myHttpHeader])
    {
      // Do something with [dict objectForKey:key];
    }
  }
}
Btw you can debug the actual headers this way:
NSHTTPURLResponse *httpResponse =
  (NSHTTPURLResponse *)aResponse;
NSLog(@"Response headers :%@",
  [httpResponse allHeaderFields]);
Happy debugging!

No comments:

Post a Comment