[英]swift: async task + completion
我對swift中的異步任務感到非常困惑。 我想做的是這樣的......
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
}
我試着這樣做:
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
}
}
}
但是,我發現UI已更新,無需等待我的計算完成。 我對使用異步隊列感到很困惑。 有人幫嗎? 謝謝。
您需要一個具有異步完成處理程序的函數。
在計算結束時調用completion()
func doLongCalculation(completion: () -> ())
{
// do something which takes a long time
completion()
}
在buttonPressed
函數中,在后台線程上調度計算函數,並在完成后返回主線程以更新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")
}
}
}
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.