For Loop - Alamofire请求以同步方式Swift4 - 执行循环等待直到异步请求返回

时间:2018-06-01 09:26:01

标签: ios synchronization alamofire swift4

for i in 0 ..< 5 {
                print("Request Number" ,i)
                Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
                    print("Finished request \(i)")
                }
            }

在这个代码示例中,有什么方法可以让我的代码以打印的方式运行

Request Number 0
Finished request 0
Request Number 1
Finished request 1
Request Number 2
Finished request 2
Request Number 3
Finished request 3
Request Number 4
Finished request 4

1 个答案:

答案 0 :(得分:1)

试试这段代码

for i in 0 ..< 5 {
            print("Request Number" ,i)
            let runLoop = CFRunLoopGetCurrent()
            Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
                print("Finished request \(i)")
                CFRunLoopStop(runLoop)
            }
            CFRunLoopRun()
        }