I am using URLSession in my iOS project. (Swift 4). The following code is only for illustration purpose.
class MyTaskManager {
...
func postMyData(...) {
let defaultSession = URLSession(configuration: .default)
dataTask = defaultSession.dataTask(with: url) { data, response, error in
...
}
dataTask.resume()
}
func getMyData(...) {
let defaultSession = URLSession(configuration: .default)
dataTask = defaultSession.dataTask(with: url) { data, response, error in
...
}
dataTask.resume()
}
}
I am trying to understand the best practice of using URLSession
in the sense of whether each function call of making HTTP request should create a new URLSession
or should I create a global one & all the calls to HTTP requests should use the same URLSession
instance?
I have studied on internet, there is an accepted answer which says I should create a new URLSession for each function/request call , there is/are also suggestions that I should reuse the same URLSession. I get confused by those accepted but conflicting answers. Could someone clarify for me the correct answer to this question?
My application doesn't have upload or download tasks, only pure RESTful request with JSON data format. No multiple configurations needed either.