如何使用Swift在iOS上同步运行两个函数

让我们提出这个场景

一个asynchronousnetworking操作的方法

func asyncMethodA() -> String? { result : String? Alamofire.manager.request(.POST, "https://www.apiweb.com/apimethod", parameters: parameters, encoding:.JSON) .response { (request, response, rawdata, error) in if (response?.statusCode == 200) { //DO SOME HEAVY LIFTING } } return result //string } 

另一种asynchronousnetworking操作的方法

 func asyncMethodB() -> String? { result : String? Alamofire.manager.request(.POST, "https://www.yetanotherapiweb.com/apimethod", parameters: parameters, encoding:.JSON) .response { (request, response, rawdata, error) in if (response?.statusCode == 200) { //DO SOME HEAVY LIFTING } } return result //string } 

一个方法,我将调用这些方法A和B,做一些操作

 func displayResult { 1) let a = asyncMethodA() 2) let b = asyncMethodB() 3) println(a + b) //some chaotic stuff might happen :( } 

(2)等待(1)运行,(3)等待(2)等(1,2和3运行同步)?

(我知道一个答案是将asyncMethodA和displayResult链接到asyncMethodB,但想知道是否有其他方法)

谢谢!。

 func anAsyncMethod(resultHandler: (result: AnyObject) -> Void) { ... } func anotherAsyncMethod(resultHandler: (result: AnyObject) -> Void) { ... } let operationQueue = NSOperationQueue() func performWithCompletionHandler(completion: (AnyObject?, AnyObject?) -> Void) { var resultOfOperation1: AnyObject? var resultOfOperation2: AnyObject? let operation1 = NSBlockOperation { let dispatchGroup = dispatch_group_create() dispatch_group_enter(dispatchGroup) self.anAsyncMethod { result in resultOfOperation1 = result dispatch_group_leave(dispatchGroup) } // wait until anAsyncMethod is completed dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER) } let operation2 = NSBlockOperation { let dispatchGroup = dispatch_group_create() dispatch_group_enter(dispatchGroup) self.anotherAsyncMethod { result in resultOfOperation2 = result dispatch_group_leave(dispatchGroup) } // wait until anotherAsyncMethod is completed dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER) } let completionOperation = NSBlockOperation { // send all results to completion callback completion(resultOfOperation1, resultOfOperation2) } // configuring interoperation dependencies operation2.addDependency(operation1) completionOperation.addDependency(operation2) operationQueue.addOperations([operation1, operation2, completionOperation], waitUntilFinished: false) } 

通过下面的内容,您可以同时启动两种asynchronous方法,并在上一次完成之后执行您的繁重工作。

 var methodAFinished = false var methodBFinished = false func asyncMethodA() -> String? { Alamofire.manager.request(.POST, "https://www.apiweb.com/apimethod", parameters: parameters, encoding:.JSON) .response { (request, response, rawdata, error) in if (response?.statusCode == 200) { methodAFinished = true doStuff() } } return result //string } 

asyncMethodB的胆量是methodBFinished = true; doStuff() methodBFinished = true; doStuff()

 func doStuff() { if methodAFinished && methodBFinished { // do crazy stuff } }