Talha Ahmad Khan Talha Ahmad Khan - 6 months ago 127
Swift Question

Swift: How to rm Alamofire get request One by One in loop

I am a beginner in swift and I have come across a case where I need to run AlamoFire GET request in a loop. But As far as i know , the Alamofire Get request is an Asynchronous call and calling it in loop will create a number of threads.

The requirement is :


  1. I have an array of URLs

  2. The array has to be traversed in a loop

  3. URL on each index has to be called through AlamoFire GET request

  4. The received data through the request will be added to an array of
    data

  5. After the last data is saved in the array, a
    CollectionView.reload call should be called



Pseudo code is as follows:

for bookmarkURL in bookmarks
Alamofire.request(.GET, bookmarkURL ).responseJSON
{ response in switch response.result {
case .Success(let JSON):
x[i] = JSON as! [String : AnyObject] // saving data

case .Failure(let error):
print("the error for \(self.bookmarkURL) is \(error) ")
}
i++
if i == bookmarks.count{
collectionView.reload()
break}
}


can anyone tell me how should I do it in sequence?

Answer
  • Make bookmarks array as class property.
  • Add a class property index to store index value (Int) while traversing the bookmarks array
  • Add a function to make API call and call it recursively.

Here is the code:

func getData() {
    var x = [[String: AnyObject]]()
    Alamofire.request(.GET, bookmarks[index]).responseJSON { response in
        switch response.result {
        case .Success(let JSON):
            x[self.index] = JSON as! [String : AnyObject] // saving data
            self.index = self.index + 1
            if self.index < self.bookmarks.count {
                self.getData()
            }else {
                self.collectionView.reloadData()
            }
        case .Failure(let error):
            print("the error for \(self.bookmarks[self.index]) is \(error) ")
            if self.index < self.bookmarks.count {
                self.getData()
            }else {
                self.collectionView.reloadData()
            }
        }
    }

}

In this way your request will be made only when previous is completed thus making it sequentially instead of parallel and you can also reload the collectionView only after the last request is completed.

Comments