Reputation: 892
I needed to set custom user agent string to sharedSession of NSURLSession. i.e. whenever I call [NSURLSession sharedSession]
, it will by default contain my custom configuration and I won't need to set it every time.
I can set the configuration to session as,
NSURLSession * session = [NSURLSession sharedSession];
NSString * userAgent = @"My String";
session.configuration.HTTPAdditionalHeaders = @{@"User-Agent": userAgent};
But I cannot find how to set the configuration to sharedSession
that can be used anytime in code.
Upvotes: 9
Views: 10638
Reputation: 2857
As per @Daniel Galasko: I added following: (just updating as its swift 2.3 code)
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let additionalHeadersDict = ["User-Agent": "User name that you want",
"Accept-Language":"lamguages",
"Accept-Encoding": "Encoding type" ]
sessionConfiguration.HTTPAdditionalHeaders = additionalHeadersDict
Thanks again to @Daniel Galasko. Please vote up his answer if you find mine useful.
Upvotes: 2
Reputation: 9867
I was also stuck in this issue, I had to change Authorization in httpHeaders. Daniel answer is right we can't change NSURLSession and its configuration once set. Solution is to set headers in NSMutableURLRequest object like
var request = NSMutableURLRequest()
request.setValue("YourAccessToken", forHTTPHeaderField: "Authorization")
Answered it might help someone.
Upvotes: 2
Reputation: 24247
Thats because you cannot modify the sharedSession. Imagine as if the sharedSession is the iOS device sharedSession and is used by all other Apps and frameworks. Makes sense for it to be non-configurable right? The documentation about it states:
The shared session uses the currently set global NSURLCache, NSHTTPCookieStorage, and NSURLCredentialStorage objects and is based on the default configuration.
What you want to do is define a custom configuration meaning you will need your own session objects with its own configuration. Thats why there is a specific constructor giving you what you need:
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration
delegate:(id<NSURLSessionDelegate>)delegate
delegateQueue:(NSOperationQueue *)queue
For brevity you can use [NSURLSessionConfiguration defaultSessionConfiguration]
to create a basic configuration and then set the additional headers there.
Naturally you will be responsible for retaining the session etc
Upvotes: 17