Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for asynchronous calls in a swift script

Im writing a swift script to be run in terminal that dispatches to the background thread a couple of operations. Without any extra effort, after all my dispatching is done, the code reaches the end of the file and quits, killing my background operations as well. What is the best way to keep the swift script alive until my background operations are finished?

The best I have come up with is the following, but I do not believe this is the best way, or even correct.

var semaphores = [dispatch_semaphore_t]()
while x {
  var semaphore = dispatch_semaphore_create(0)
  semaphores.append(semaphore)
  dispatch_background {
    //do lengthy operation
    dispatch_semaphore_signal(semaphore)
  }
}

for semaphore in semaphores {
  dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
like image 795
Gagan Singh Avatar asked Feb 27 '15 20:02

Gagan Singh


2 Answers

In addition to using dispatch_groups, you can also do the following:

yourAsyncTask(completion: {
    exit(0)
})

RunLoop.main.run()

Some resources:

  • RunLoop docs
  • Example from the swift-sh project
  • Exit code meanings
like image 65
jason z Avatar answered Oct 16 '22 08:10

jason z


Thanks to Aaron Brager, who linked to Multiple workers in Swift Command Line Tool ,

which is what I used to find my answer, using dispatch_groups to solve the problem.

like image 37
Gagan Singh Avatar answered Oct 16 '22 07:10

Gagan Singh