Configure NSURLSession sharedSession configuration

I needed to set a user agent user string for sharedSession NSURLSession. that is, whenever I call [NSURLSession sharedSession] , it will by default contain my custom configuration, and I will not need to install it every time.

I can configure the session as,

 NSURLSession * session = [NSURLSession sharedSession]; NSString * userAgent = @"My String"; session.configuration.HTTPAdditionalHeaders = @{@"User-Agent": userAgent}; 

But I cannot find how to configure the configuration for sharedSession , which can be used at any time in the code.

+5
source share
3 answers

This is because you cannot change sharedSession. Imagine that sharedSession is an iOS device sharedSession and is used by all other applications and frameworks. Does it make sense that it is not configurable correctly? The documentation says about it:

The general session uses the currently installed global NSURLCache, NSHTTPCookieStorage and NSURLCredentialStorage Objects and are based by default.

What you want to do is define a custom configuration in which you will need your own session objects with your own configuration. This is why there is a specific constructor that gives 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 additional headers there.

Naturally, you are responsible for maintaining the session, etc.

+12
source

I am also stuck in this problem, I had to change the authorization in httpHeaders. Daniel is right, we cannot change the NSURLSession and its configuration after installation. The solution is to set headers in an NSMutableURLRequest object, e.g.

 var request = NSMutableURLRequest() request.setValue("YourAccessToken", forHTTPHeaderField: "Authorization") 

Answered this might help someone.

+1
source

According to @ Daniel Galasco: I added the following: (just updating it as quick code 2.3)

 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 @ Daniel Galasco. Please vote for his answer if you find mine helpful.

+1
source

Source: https://habr.com/ru/post/1208414/


All Articles