swift: async task + completion

删除回忆录丶 提交于 2019-12-22 07:04:59

问题


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.


回答1:


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")
      }
    }
  }
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/39250589/swift-async-task-completion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!