5

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.

user6539552
  • 1,331
  • 2
  • 19
  • 39

2 Answers2

9

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")
      }
    }
  }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
0
dispatch_queue_t dispatchqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(dispatchqueue, ^(void){
    while ([self calculate]) {
        NSLog(@"calculation finished");
        dispatch_async(dispatch_get_main_queue(), ^{
            // update the UI
        });
    }
});

- (BOOL)calculate
{
    //do calculation
    //return true or false based on calculation success or failure
    return true;
}
Jeyamahesan
  • 1,101
  • 7
  • 15