What's the correct usage of URLSession, create new one or reuse same one
You should create a shared instance of the data session and use the same creating multiple tasks because it's rarely the case that you need to have a different configuration for an api.
I suggest and use the shared instance of data session for getting data from an api.
class MyTaskManager {
static let sessionManager: URLSession = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 30 // seconds
configuration.timeoutIntervalForResource = 30 // seconds
return URLSession(configuration: configuration)
}()
func postMyData(...) {
dataTask = sessionManager.dataTask(with: url) { data, response, error in
...
}
dataTask.resume()
}
func getMyData(...) {
dataTask = sessionManager.dataTask(with: url) { data, response, error in
...
}
dataTask.resume()
}
}
The benefit of this is that I had to create the session only once, so that will save repetition of same code and also the process to initialise the same thing again per api request. This will be more helpful in case you need to more custom configuration of the session.