2

I'm currently learning about callbacks in Swift and am trying to understand something very basic. I can't seem to find a straight answer on this anywhere.

I understand that if I do:

URLSession.dataTask(with: URLRequest) { data, response, error in }

it will perform an asynchronous network request, after which I can do my own work with the result in the completion handler.

However, let's say that I want to write my own function that does some sort of background task. Would simply having a closure as a parameter to the function (that gets called in the function body) be enough to make the function work asynchronously? Or would I have to get into calling GCD method(s) in the function body as well?

Drew
  • 674
  • 5
  • 14
  • Yes, you'll need to make sure it is on another thread; http://stackoverflow.com/questions/24056205/how-to-use-background-thread-in-swift. Calling a function from a parameter does not make it asynchronous. http://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean – Dave Thomas Oct 20 '16 at 03:50
  • to make your code work in background you need to use GCD .. .dataTask send an asynchronous request by default – Abdul Waheed Oct 20 '16 at 03:51

1 Answers1

3

Simply having a callback parameter has no affect on the implementation of the method. If you wish to make it asynchronous then you need to take explicit steps to make it asynchronous. This can be done using grand central dispatch, operation queues, or calling other asynchronous methods.

rmaddy
  • 314,917
  • 42
  • 532
  • 579