Ios – swift: async task + completion

dispatch-asynciosswiftswift2

I got quite a lot of confusion on async tasks in swift. What i want to do is something like this…

 func buttonPressed(button: UIButton) {
   // display an "animation" tell the user that it is calculating (do not want to freeze the screen
   // do some calculations (take very long time) at the background
   // the calculations result are needed to update the UI
 }

I tried to do something like this:

func buttonPressed(button: UIButton) {
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    dispatch_async(queue) { () -> Void in
       // display the animation of "updating"
       // do the math here
        dispatch_async(dispatch_get_main_queue(), {
          // update the UI
       }
    }
}

However, I found that the UI is updated without waiting my calculation to be completed. I am quite confused on the use of async queue. Anyone help? Thanks.

Best Answer

You need a function with a asynchronous completion handler.

At the end of the calculation call completion()

func doLongCalculation(completion: () -> ())
{
  // do something which takes a long time
  completion()
}

In the buttonPressed function dispatch the calculate function on a background thread and after completion back to the main thread to update the UI

func buttonPressed(button: UIButton) {
  // display the animation of "updating"
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {  
    self.doLongCalculation {
      dispatch_async(dispatch_get_main_queue()) {
        // update the UI
        print("completed")
      }
    }
  }
}