Hi so I have this problem where I have an array filled with string (for example: [dog,cat,girraffe,cow]) and I am to use this id to make an API call to some website to get the image from that site. I need the result to be in same order as the array.
For this example I need the output to be like this if i print both arrays it should be like this: theString - dog, cat, girraffe, cow age - 5, 10, 20, 5 <-- the ordering corresponds to the animal
but instead, I get the age outputs like: age - 5, 20, 10, 5 OR age - 10, 20, 5, 5 etc.
I pretty much the role the dice until i get the output to be in order.
since each API call is async, the ordering is always random when it comes to the age. I have been stuck on this issue for days now, not quite sure how to go about it..
example code:
let theString = ["dog", "cat", "girraffe", "cow"]
var age = Array() // to store the ages of the animal in order
override func viewDidLoad() {
super.viewDidLoad()
//make the call 4 times
for each in theString{
doAPICall(name:each)
print(age)//the output is not in order
}
}
func doAPICall(name: String){
let animal = name
let urlString:String = "https://somewebsite.com/api/"+ animal
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url, completionHandler: {
(data, response, error) in
if error != nil {
print(error!.localizedDescription)
} else{
do{
let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
let age = parsedData["age"] as! Int
self.age.append(age) //appends the age to the array
} catch let error as NSError {
print(error)
}
}//end else
})
task.resume()
}
In short, I need some way to tell the for loop or the async call to wait until the previous one is complete before moving onto the next
