NSURLSessionConfiguration HTTPAdditionalHeaders not set
Asked Answered
E

2

7

Authorization header is set in NSURLSessionConfiguration, however it is not attached to NSURLSessionDataTask. Is this a bug in Foundation framework?

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
[configuration setHTTPAdditionalHeaders:@{@"Authorization":@"123"}];

// Initialize session with NSURLSessionConfiguration
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];

[sessionTask resume];
Enceladus answered 15/7, 2014 at 6:56 Comment(2)
You got any solution?Mcalpine
this works for me smoothly (on iOS 15)Fick
D
5

I try this in Swift and it works

    var sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
    var xHTTPAdditionalHeaders: [NSObject : AnyObject] = ["X-test":"taly"]
    sessionConfig.HTTPAdditionalHeaders = xHTTPAdditionalHeaders
    let session = NSURLSession(configuration: sessionConfig)

    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
Dowden answered 15/7, 2014 at 11:45 Comment(2)
Works for X-test but won't work for Authorization. See Dongjin Suh answer.Celinacelinda
config.httpAdditionalHeaders = [ "authorization": "token abcd"] works for me smoothly (iOS 15).Fick
G
6

In the NSURLSessionConfiguration document,

An NSURLSession object is designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers:

Authorization

Connection

Host

WWW-Authenticate

Gandy answered 3/3, 2016 at 3:4 Comment(1)
This doc still exists in 2021, but the instructions re: Authorization field seem to be irrelevant.Fick
D
5

I try this in Swift and it works

    var sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
    var xHTTPAdditionalHeaders: [NSObject : AnyObject] = ["X-test":"taly"]
    sessionConfig.HTTPAdditionalHeaders = xHTTPAdditionalHeaders
    let session = NSURLSession(configuration: sessionConfig)

    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
Dowden answered 15/7, 2014 at 11:45 Comment(2)
Works for X-test but won't work for Authorization. See Dongjin Suh answer.Celinacelinda
config.httpAdditionalHeaders = [ "authorization": "token abcd"] works for me smoothly (iOS 15).Fick

© 2022 - 2024 — McMap. All rights reserved.