Fr4nc3sc0NL Fr4nc3sc0NL - 7 months ago 62
Swift Question

Best/most common way to update UI from background thread

I was posting notifications to the

NSNotficiationCenter
everytime I needed to get out of a closure to update the UI, but this started to get a bit tedious and made me wondering if there was a better way. After a quick search I found out that you can just dispatch to the main queue like this:

dispatch_async(dispatch_get_main_queue()) {
// update some UI
}


This approach is less code for sure, but I wonder if it improves readability. So my question is, what is considered "the way to go" in Swift to update UI from a background thread?

Answer

This is the way to go:

let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
   // do some background task
   dispatch_async(dispatch_get_main_queue()) {
      // update some UI
   }
}