Run multiple URLRequest in for loop execute one after previous finished

654 views Asked by At

In my app I have a task in which user will enter the from and to date and the url will fetch the data. Each URL will return large sized JSON string from the server.

Problem arises when user enters larger date interval which makes the server to hang. In android version of the app I used AsyncTask to done this. In that I split the requests in to multiple if user enters large date interval. I use for loop to fetch data for each day and publish the progress in onProgressUpdate after each day task completed.

In swift also I need to use multiple data tasks in a for loop and publish the results.

for i in 0 ..< dates.count {
   // Getting response from server //
   let response = getResponse(imei: sImei, date: dates[i])
   parseResponse(response)
}

This is how I planned on doing this. But don't know how to implement this.

I saw some suggestions to use DispatchGroup. I'm not familiar with that. So please guide me to achieve my task.

Note: Giving large date interval in single dataTask will choke my server. Because, it's a low end server. So I have to query data for individual dates and combine them.

2

There are 2 answers

0
yogesh wadhwa On

Use Recursion: initially i = 0 .

 func callApi( i : Int){

    if(dates.count > i){

   // After Getting response from server //

        self.callApi(i: i + 1)

 }

}
0
Mohamed Adly On

Try to make a loop to generate NSBlockOperation and use addDependency to the previous operation.

var prevOperation
for i in 0 ..< dates.count {

    var operation = NSBlockOperation() {
        // Getting response from server //
        let response = getResponse(imei: sImei, date: dates[i])
        parseResponse(response)
    }

    if(i>0) {
        operation.addDependency(prevOperation)
    }
    prevOperation=operation;
}