gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:14 24 4
gpt4 key购买 nike

让我们提出这个场景

具有异步网络操作的方法

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com