gpt4 book ai didi

ios - 如何使用 Alamofire 制定一个良好的模式来控制多个请求依赖关系?比如request2需要request1的响应

转载 作者:行者123 更新时间:2023-11-30 13:55:04 25 4
gpt4 key购买 nike

我使用 Alamofire 同时发送多个请求。但是请求A需要请求B的响应名为token。我举个例子:

var token = "111111111111"

let URLString1 = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString1, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
print("http1: \(JSON)")
token = "22222222222"
case .Failure(let error):
print("Request failed with error: \(error)")
}
}

//I want to wait for request1's response and get the new token value.
let URLString2 = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString2, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
print("http2: \(JSON)")
print("token: \(token)")
case .Failure(let error):
print("Request failed with error: \(error)")
}
}

我不想将 request2 放在 request1 的成功中。所以现在我的解决方案是:我给出一个名为 tokenChange 的变量。我有一个数组来存储所有需要 token 的请求。当 token 更改时,我从数组中将它们一一发送。但这个解决方案并不优雅。那么有没有一个好的模式来控制这个呢?

最佳答案

我发现这个方法dispatch_semaphore_signal。它可以解决我的问题。那么还有其他方法吗?

var token = "111111"

let group = dispatch_group_create();

dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in
let semaphore = dispatch_semaphore_create(0)
//token is 111111
let URLString = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
print("http1: \(JSON)--class:")
token = "222222"
print("\n")
dispatch_semaphore_signal(semaphore)
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)

//token is 222222
let URLString2 = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString2, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
print("http2: \(JSON)--class:")
print("\n")
print ("token is:\(token)")
case .Failure(let error):
print("Request failed with error: \(error)")
}
}

//token is 2222222
let URLString3 = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString3, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
// token = (JSON["args"]!!["value"]) as! String
print("http3: \(JSON)--class:")
print("\n")
print ("token is:\(token)")
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
}

dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in
NSLog("finish");
}

关于ios - 如何使用 Alamofire 制定一个良好的模式来控制多个请求依赖关系?比如request2需要request1的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33731195/

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