Eleazer Toluan
Eleazer Toluan

Reputation: 235

Swift 2 For Loop with asynchronous network request continue looping after the response

I'm trying to send a thousands of http request but my app is crashing due to memory issue. "terminated due to memory issue". So I wanted to wait the response before continue looping to send another request.

for i in 0 ..< 10000 {

    Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
        print("Finished request \(i)")
        // Continue the looping
    }
}

Upvotes: 1

Views: 128

Answers (1)

Kamran
Kamran

Reputation: 15258

You can do simple recursion as below.

func makeRequest(for index: Int) {
    guard index < 10000 else { return }
    Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { [weak self] response in
        print("Finished request \(index)")
        self?.makeRequest(for: index + 1)
    }
}

and then start from zero or whatever index as below,

self.makeRequest(for: 0)

Upvotes: 1

Related Questions