0

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.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Praveen Kumar
  • 547
  • 1
  • 7
  • 33
  • please read this post https://stackoverflow.com/questions/42484281/waiting-until-the-task-finishes/42484761#42484761. It might help you. – Usman Javed Sep 12 '17 at 11:38
  • Your request are independent of each other, right? If you're not using the results of one request before you would send off the next one, you're better off running those concurrently and not waiting for a request to finish before starting the next one. – Dávid Pásztor Sep 12 '17 at 12:32

2 Answers2

1

Use Recursion: initially i = 0 .

 func callApi( i : Int){

    if(dates.count > i){

   // After Getting response from server //

        self.callApi(i: i + 1)

 }

}
yogesh wadhwa
  • 711
  • 8
  • 16
0

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;
}
Mohamed Adly
  • 210
  • 1
  • 8