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.
A session configuration that uses no persistent storage for caches, cookies, or credentials. class func background(withIdentifier: String) -> URLSessionConfiguration. Creates a session configuration object that allows HTTP and HTTPS uploads or downloads to be performed in the background.
The NSURLSession class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. Your app can also use this API to perform background downloads when your app isn't running or, in iOS, while your app is suspended.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With