Search code examples
iosnsurlsession

What's the correct usage of URLSession, create new one or reuse same one


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.


Solution

  • 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.