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 :
The array has to be traversed in a loop
URL on each index has to be called through AlamoFire GET request
The received data through the request will be added to an array of data
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?
Navigate to the directory containing your AlamofireSwiftyJSONSample project by using the cd command: It will create Podfile in your project's directory. Edit the pod file with your pods which you want to use and must remember the targets. Add pods to the particular target where you want to use that pod.
So if you’re having trouble debugging an API call in your app, use let request = Alamofire.request(...)then debugPrint(request)after the completion handler(s).
Alamofire is an HTTP networking library written in Swift. SwiftyJSON makes it easy to deal with JSON data in Swift. CocoaPods runs on ruby so update your system.
This post presents an implementation of HTTP requests in Swift without needing Alamofire, a Cocoapod, or other third-party library. Following the method in this post will allow you to make GET and POST HTTP requests to a url. Why Not Use Alamofire and Cocoapods for HTTP requests?
bookmarks
array as class property.index
to store index value (Int
) while traversing the bookmarks
arrayHere 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With