swift: tâche asynchronous + achèvement

J'ai eu beaucoup de confusion sur les tâches asynchronouss dans swift. Ce que je veux faire est quelque chose comme ça …

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 } 

J'ai essayé de faire quelque chose comme ça:

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

Cependant, j'ai trouvé que l'interface user est mise à jour sans attendre que mon calcul soit terminé. Je suis assez confus sur l'utilisation de la queue asynchronous. Quelqu'un aide-t-il? Merci.

Vous avez besoin d'une fonction avec un gestionnaire d'achèvement asynchronous.

A la fin de la fin de l'appel de calcul completion()

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

Dans la fonction buttonPressed fonction calculate est buttonPressed sur un thread d'arrière-plan et, une fois le buttonPressed terminé, sur le thread principal pour mettre à jour l'interface user.

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