swift: async task + completion
Asked Answered
P

2

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.

Philip answered 31/8, 2016 at 13:10 Comment(2)
Is // do the math here making an request to a server?Masturbate
No, just do a lot of calculation which takes quite a long time that i do not want to freeze the screen... :(Philip
C
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")
      }
    }
  }
}
Creeper answered 31/8, 2016 at 13:48 Comment(0)
G
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;
}
Guayaquil answered 31/8, 2016 at 13:33 Comment(1)
Waiting is a pretty bad way.Creeper

© 2022 - 2024 — McMap. All rights reserved.