Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift wait for closure thread to finish

I'm using a very simple swift project created with SPM where it includes Alamofire.

main.swift:

import Alamofire

Alamofire.request("https://google.com").responseString(queue: queue) { response in
            print("\(response.result.isSuccess)")
}

The closure is never executed if I don't use a lock. Is there a way to instruct to wait for all threads or that specific thread before exiting?

I'm aware this can be easily achieved using Playgrounds.

like image 893
Leonardo Marques Avatar asked Oct 31 '17 17:10

Leonardo Marques


2 Answers

Simplest way to wait for an async task is to use a semaphore:

let semaphore = DispatchSemaphore(value: 0)

doSomethingAsync {
    semaphore.signal()
}

semaphore.wait()

// your code will not get here until the async task completes

Alternatively, if you're waiting for multiple tasks, you can use a dispatch group:

let group = DispatchGroup()

group.enter()
doAsyncTask1 {
    group.leave()
}

group.enter()
doAsyncTask2 {
    group.leave()
}

group.wait()

// You won't get here until all your tasks are done
like image 93
Charles Srstka Avatar answered Nov 01 '22 15:11

Charles Srstka


For Swift 3

let group = DispatchGroup()
group.enter()
DispatchQueue.global(qos: .userInitiated).async {
    // Do work asyncly and call group.leave() after you are done
    group.leave()
}
group.notify(queue: .main, execute: {
    // This will be called when block ends             
})

This code will be helpful when you need to execute some code after some task is done.

Please add details about your question, then I can help you more.

like image 28
Nikhil Manapure Avatar answered Nov 01 '22 17:11

Nikhil Manapure