Search code examples
iosnsurlsessionnsurlsessiondownloadtasknsurlsessionconfiguration

NSURLSession & NSURLSessionConfig - Discarding Config Headers


I am having an issue with NSURLSession & NSURLSessionConfiguration and I am not sure if it is my code or I have an incorrect understanding of how the framework behaves.

The issue I am facing is that headers I set at the session level are not present in the NSURLSessionTask created from the session.

Here is a small example:

NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPAdditionalHeaders = @{ @"TestHeader" : @"TextHeaderValue" };

NSURLSession* session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDownloadTask* task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://www.google.com"]];

NSLog(@"%@",task.originalRequest.allHTTPHeaderFields.description);
NSLog(@"%@",task.currentRequest.allHTTPHeaderFields.description);
NSLog(@"%@",session.configuration.HTTPAdditionalHeaders);

The code above outputs:

(null)
(null)
{TestHeader = TextHeaderValue}

From my understanding of the documentation, any task or request created from the session should inherent the HTTPHeaders from the session. Is my understanding correct? If so, can anyone see what I am doing wrong?


Solution

  • The header is being sent according to Charles Proxy:
    "TestHeader TextHeaderValue".

    This seems to be a display problem with the way headers are set in NSURLSessionConfiguration and NSURLSession. Perhaps one should not assume that the allHTTPHeaderFields property is set when using NSURLSession.