view raw
Azhar Bandri Azhar Bandri - 9 months ago 199
iOS Question

Set configuration of NSURLSession sharedSession

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
that can be used anytime in code.


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
                             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