2

I want a URLSession to perform an HTTP network call and parse its JSON response. I'm following an example which more or less matches my scenario, and I found this code:

let request = URLRequest(url: url)
let dataTask = myUrlSession.dataTask(with: request, completionHandler: { [unowned self] (data, response, error) in
  guard let data = data else {
    OperationQueue.main.addOperation {
      completion(nil, error)
    }
    return
  }
  self.parseJsonResponse(data, completion: completion)
})

There is no explanation about a couple of things I'd like to understand:

  • If request is not set any specific property, is there any benefit in using it instead of calling myUrlSession.dataTask(with: completionHandler:) providing just the URL instead?

  • Why is OperationQueue.main.addOperation used in the completion handler? I need to be able to cancel the network operation depending on user interaction, but should I do like that? And then, how should I cancel the operation if I need it?

For this last point, I was thinking about this other version:

let dataTask = myUrlSession.dataTask(with: url, completionHandler: { [unowned self] (data, response, error) in
  guard let data = data else {
    completion(nil, error)
    return
  }
  self.parseJsonResponse(data, completion: completion)
})

And if I need to cancel the task:

dataTask.cancel()

Is this an appropriate approach? Or would it be better to use an OperationQueue?

AppsDev
  • 12,319
  • 23
  • 93
  • 186

0 Answers0