Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 766
Azhar Bandri Avatar asked Dec 05 '14 09:12

Azhar Bandri


People also ask

What is Urlsession configuration?

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.

What is NSURLSession in Swift?

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.


1 Answers

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

like image 199
Daniel Galasko Avatar answered Nov 12 '22 23:11

Daniel Galasko