gpt4 book ai didi

swift - 完成另一个 Alamofire 请求后运行 Alamofire 请求

转载 作者:行者123 更新时间:2023-11-30 10:35:32 27 4
gpt4 key购买 nike

我想运行一个 Alamofire 请求,该请求使用先前 Alamofire 请求的结果作为参数。为了简单起见:

    //Code1
Alamofire.request("URL", method: HTTPMethod.post, parameters: ["id": id as NSString)], encoding: URLEncoding.httpBody).response(completionHandler: { (response) in
let json = response.data
do {
print("This should be First")
let data = try JSON(data: json!)
let alllastmessages = data["Messages"].arrayValue
for i in 0..<alllastmessages.count {
self.List.append(alllastmessages[i]["message"].stringValue)
}}
catch _{}
})
//End Code1

//Code2
print("This should be Last")
for i in 0..<List.count {
Alamofire.request("URL2", method: .post , parameters: ["id": id as NSString] , encoding: URLEncoding.httpBody).response(completionHandler: { (response) in
//Do Something
})
self.tableView.reloadData()
}
//End Code2

(此代码已简化,我只是在寻找一种方法使 Code1 在 Code2 之前运行)

最佳答案

IMO 最简单的方法是使用 DispatchGroup,您可以在此处阅读更多相关信息:https://developer.apple.com/documentation/dispatch/dispatchgroup

这里有一些对我来说效果很好的代码:

    DispatchQueue.global(qos: .userInitiated).async {
let group = DispatchGroup()
group.enter()

print("\(Date()) Start request 1!")
Alamofire.request("https://github.com/CosmicMind/Material",
method: .get ,
parameters: [:] , encoding: URLEncoding.httpBody).response(completionHandler: { (response) in
print("\(Date()) Request 1 completed!")
group.leave()
})

group.wait()

print("\(Date()) Start request 2!")
Alamofire.request("https://github.com/CosmicMind/Material",
method: .get ,
parameters: [:] , encoding: URLEncoding.httpBody).response(completionHandler: { (response) in
print("\(Date()) Request 2 completed!")
})
}

打印:

2017-12-22 18:24:45 +0000 Start request 1!
2017-12-22 18:24:47 +0000 Request 1 completed!
2017-12-22 18:24:47 +0000 Start request 2!
2017-12-22 18:24:49 +0000 Request 2 completed!

关于swift - 完成另一个 Alamofire 请求后运行 Alamofire 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58141259/

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