Search code examples
iphoneiosobjective-chttpapi-key

API key must be passed as the API-Key header in every request


I want to pass API-Key in the header in every request.

 NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
NSLog(@"%@",request );
[request setHTTPMethod: @"POST"];

[request addValue:@"4eaa90d7175e98732543994eaa90d717" forHTTPHeaderField:@"API-Key"] ;

request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:
           NSURLRequestUseProtocolCachePolicy timeoutInterval:100];

NSLog(@"%@",url);
NSLog(@"%@",[request allHTTPHeaderFields]);

The allHTTPHeaderFields is null. am i missing something?


Solution

  • You first initialize request with a NSMutableURLRequest which has the header field and then you overwrite it with an NSURLRequest that doesn't have the API key in the header field. Just get rid of this line:

    request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:
               NSURLRequestUseProtocolCachePolicy timeoutInterval:100];