ios - 如何使用 Swift 在 iOS 上通过异步操作同步运行两个函数

标签 ios iphone asynchronous swift alamofire

让我们提出这个场景

具有异步网络操作的方法

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

}

另一种异步网络操作的方法

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

关于ios - 如何使用 Swift 在 iOS 上通过异步操作同步运行两个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27177268/

相关文章:

php - Laravel 调度作业不异步运行,阻碍执行

ios - 自定义 UIView 的边框绘制不流畅

iphone - Objective-C 中的 “category” 是什么?

Javascript,如何实现从多个工作人员调用的 "blocking"函数

javascript - “this”在类里面未定义

iphone - 多少评分足以显示 App Store 上应用程序的平均值?

ios - 有没有办法呈现已经加载的 View Controller ?

objective-c - 同时使用 UILongPressGestureRecognizer 和 UISwipeGestureRecognizer

ios - 为 iPhone 应用程序添加加密,它如何影响批准?

ios编程: Keeping user configuration in memory vs storage