AppsDev
AppsDev

Reputation: 12499

Is keeping a reference to an URLSessionTask necessary?

I've reading several examples related to URLSession and URLSessionTask where code snippets were shown and/or the sample project was available to download. Examples were about the quite common scenario of requesting some info to a REST service by using URLSessionDataTask, most of them having classes similar to this:

var defaultSession: URLSession
var dataTask: URLSessionDataTask?

override init() {
   let configuration = URLSessionConfiguration.default
   self.defaultSession = URLSession(configuration: configuration, delegate: nil, delegateQueue: self.operationQueue)

   super.init()
}

func callService(with searchUrl: URL, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
   dataTask = defaultSession.dataTask(with: searchUrl, completionHandler: completion)
   dataTask?.resume()
}

I find that usually a reference to dataTask is kept but it is not used at any other place out of that func. Which would be the reasons to keep a reference to the dataTask?

Upvotes: 3

Views: 917

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

There's no need to keep reference to a URLSessionDataTask instance if you simply want to execute the data task once. You can simply do defaultSession.dataTask(with: searchUrl, completionHandler: completion).resume()

However, keeping a reference to a URLSessionDataTask instance can be useful in case you want to suspend or cancel it before it finishes execution.

There also seems to be a typo in your callService method. The withUrl input parameter isn't used anywhere, but there's a reference to searchUrl, which isn't an input parameter, so I suppose you wanted to call the URL input parameter searchUrl.

func callService(with searchUrl: URL, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
   defaultSession.dataTask(with: searchUrl, completionHandler: completion).resume()
}

Upvotes: 6

Related Questions