gpt4 book ai didi

swift - Alamofire的请求数量一个接一个

转载 作者:可可西里 更新时间:2023-11-01 00:59:00 34 4
gpt4 key购买 nike

我有许多请求,我想在没有嵌套意大利面条代码的情况下一个接一个地调用。

我已经用串行调度队列试过了

let queue = dispatch_queue_create("label", DISPATCH_QUEUE_SERIAL)

Alamofire.request(Router.Countries).responseString { (response:Response<String, NSError>) in
print(1)
}

Alamofire.request(Router.Countries).responseString { (response:Response<String, NSError>) in
print(2)
}

Alamofire.request(Router.Countries).responseString { (response:Response<String, NSError>) in
print(3)
}

但不幸的是,这不起作用。此输出可以是 1,3,2 或 3,1,2 或任何其他组合。

一个接一个地获得输出 1,2,3 的最佳方法是什么。

最佳答案

好的,我最终编写了自己的实现。

我创建了一个 RequestChain 类,它以 Alamofire.Request 作为参数

class RequestChain {
typealias CompletionHandler = (success:Bool, errorResult:ErrorResult?) -> Void

struct ErrorResult {
let request:Request?
let error:ErrorType?
}

private var requests:[Request] = []

init(requests:[Request]) {
self.requests = requests
}

func start(completionHandler:CompletionHandler) {
if let request = requests.first {
request.response(completionHandler: { (_, _, _, error) in
if error != nil {
completionHandler(success: false, errorResult: ErrorResult(request: request, error: error))
return
}
self.requests.removeFirst()
self.start(completionHandler)
})
request.resume()
}else {
completionHandler(success: true, errorResult: nil)
return
}

}
}

我是这样用的

let r1 = Alamofire.request(Router.Countries).responseArray(keyPath: "endpoints") { (response: Response<[CountryModel],NSError>) in
print("1")
}

let r2 = Alamofire.request(Router.Countries).responseArray(keyPath: "endpoints") { (response: Response<[CountryModel],NSError>) in
print("2")
}

let r3 = Alamofire.request(Router.Countries).responseArray(keyPath: "endpoints") { (response: Response<[CountryModel],NSError>) in
print("3")
}

let chain = RequestChain(requests: [r1,r2,r3])

chain.start { (success, errorResult) in
if success {
print("all have been success")
}else {
print("failed with error \(errorResult?.error) for request \(errorResult?.request)")
}


}

重要的是你告诉经理不要立即执行请求

    let manager = Manager.sharedInstance
manager.startRequestsImmediately = false

希望对别人有帮助

关于swift - Alamofire的请求数量一个接一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38630939/

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