Using threads to update UI with Swift Using threads to update UI with Swift multithreading multithreading

Using threads to update UI with Swift


Swift 3.0 + version

DispatchQueue.main.async() {    // your UI update code}

Posted this because XCode cannot suggest the correct syntax from swift 2.0 version


There is GCD. Here is a basic usage:

for page in listOfPages {    var label = NSTextField()    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {        let result = getInformationFromPage(page)        dispatch_async(dispatch_get_main_queue()) {            label.stringValue = result        }    }}

dispatch_async function asynchronously runs the block of code on the given queue. In first dispatch_async call we dispatch the code to run on background queue. After we get result we update label on main queue with that result