gpt4 book ai didi

ios - 如何在 Swift 中优化链式异步请求

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

我有像 A->B->C 这样的请求链接代码,我正在使用 URLSession 所有请求都按正确的顺序和预期的行为完成。但我想知道如何优化这个链接,因为它看起来很复杂而且不可重用。我正在寻找如何以更灵活的方式进行这种链接的建议。

我的代码:

URLSession.shared.dataTask(with: URLRequest(url: URL(string: "first")!)){ data , res , err in
let second = URLRequest(url: URL(string: "second")!)
URLSession.shared.dataTask(with: second){ data , res , err in
let third = URLRequest(url: URL(string: "second")!)
URLSession.shared.dataTask(with:third){ data , res , err in
}.resume()
}.resume()
}.resume()

最佳答案

实际上,您可以像下面这样使用 OperationQueues 来使用依赖项:

func operationQueueWithBlockandCancel(){

let mainQueue = OperationQueue.main

let operationBlock1 = BlockOperation()
let operationBlock2 = BlockOperation()
let operationBlock3 = BlockOperation()


operationBlock1.addExecutionBlock {
//Any task
}

operationBlock2.addExecutionBlock {
//Any task
}


operationBlock3.addExecutionBlock {
//Any task
}

//Add dependency as required
operationBlock3.addDependency(operationBlock2)
operationBlock2.addDependency(operationBlock1)

opQueue.addOperations([operationBlock2,operationBlock1,operationBlock3,], waitUntilFinished: false)

}

关于ios - 如何在 Swift 中优化链式异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43389407/

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