So, I have a json get request which gets all horse objects of class Horse. This works successfully. I have a completion handler which is supposed to let me use the horses object again in another view where I call the getHorses request but when I try to get those objects into another array it does not append them. Why is that the case?
Here is my code:
func getJSONHorses (completion: @escaping ([Horse])->[Horse]) { //Message<[Horse]>
let url = "http://localhost:8083/horses"
if let url = URL(string: url)
{
let task = session.dataTask(with: url) { data, response, error in
if error != nil || data == nil {
print("Client error!")
return
}
let str = String(decoding: data!, as: UTF8.self)
print(str)
do {
print("nothing")
let json = try JSONDecoder().decode(Message<[Horse]>.self, from: data!)
print(json.model?.count as Any)
// print(json.model as Horse)
// print(json.self.model)
// print(json.model)
print(json.model as Any)
print("something")
completion(json.model!)
} catch {
print("JSON error: \(error)")
print("erroooorrrrrr")
}
}
task.resume()
print("finished")
}
}
Here I use the function:
print("Startttt")
backEnd.getJSONHorses(completion:{(horse) in
for h in horse {
self.horses.append(h)
}
print(horse.count)
self.horses = horse
//print(horse.count as Any
return horse
})
print(horses.count)
print("END")
THe horses array is 0 even when I try to append the horses to it.