Swift Serial Dispatch Block只有在委托之后才能完成

这是很难解释的。 我正在创build一个串行队列来处理我的应用程序中的一些工作。 想象一下,我做这样的事情:

dispatch_async(myQueue, { () -> Void in self.SendSMS(); }); dispatch_async(myQueue, { () -> Void in self.SendEmail(); }); 

现在我想要做的只是在委托(SendSMS委托)完成工作之后调用self.SendEmail。

有一个简单的方法来做到这一点?

非常感谢

假设SendSMS是一个asynchronous方法,我build议改变SendSMS采取一个完成处理程序closures:

 // define property to hold closure var smsCompletionHandler: (()->())? // when you initiate the process, squirrel away the completion handler func sendSMSWithCompletion(completion: (()->())?) { smsCompletionHandler = completion // initiate SMS } // when the SMS delegate method is called, call that completion closure func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) { // do whatever you want when done // finally, call completion handler and then release it smsCompletionHandler?() smsCompletionHandler = nil } 

因此,您可以这样调用它,将sendEmail放入sendSMS的完成closures中:

 self.sendSMSWithCompletion() { self.sendEmail() } 

我不知道你的sendSMSsendEmail在做什么,但是如果你调用了MessageUI框架,你通常会在主队列上这样做。 但是,如果你真的需要在专门的队列上进行上述操作,那么请随时派遣。 但希望能够说明这个概念:(a)供应完成处理程序closures; (b)保存它,以便您的代表可以调用它; 和(三)当委托被调用时,使用该属性,然后重置它。

一种方法来做到这一点,它的工作原理是把:

 dispatch_async(myQueue, { () -> Void in self.SendEmail(); }); 

在代表结束时。 但我不知道这是否是唯一的方法来做到这一点。

干杯

是的,你可以这样做,接下来的步骤:

 // create tasks group handle let taskGroup = dispatch_group_create() let mainQueue = dispatch_get_main_queue() // write your blocks in needed order dispatch_group_async(taskGroup, mainQueue) { [weak self] in // execute your code // don't forget to use self with optional, ie: self!.property or function self!.SendSMS() } dispatch_group_async(taskGroup, mainQueue) { [weak self] in self!.SendEmail() } // and of course you need to catch completion of this task group dispatch_group_notify(taskGroup, mainQueue) { println("All work is done, milord!") } 

UPD。 上面的解决scheme是关于无命令的asynchronous执行,因为命名和两个之一可以比声明的命令更早完成。 您需要使用依赖关系作为持续执行的解决scheme。 我正在讨论multithreading的订购,而不是完成closures或执行程序模式。 请注意,有多个案例可以做到这一点。 其中之一 – 下面:

 let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(queue) { dispatch_sync(queue) {[weak self] in self?.SendSMS() } dispatch_sync(queue) {[weak self] in self?.SendEmail() // here you need to call your completion of success function in main thread } } 

请注意,函数中的代码必须存在于同一个队列中,并使用同步方法来处理服务器请求。 但这是另一回事了)