Spent the good part of three weeks trying to solve this problem. I programmed my swift JSON file and successfully brought down JSON data from our website and printed it in the output. What I can't do is get the JSON data out of my func() and into my ViewController! I am missing something and I don't know what it is.
I have a JSON model of the data that is a struct and decodable. That all works great. I have a JSON manager (code below) that brings the data down using a URLSession and parses the data using a JSON decoder. That all works.
I just don't know how to make the data available outside of the URLSession closure to be used in my ViewController file. As an example I would like to do something like this: textField.text = json[0].acf.common_name in my viewController file.
What am I missing?
func getDate() {
let task = URLSession.shared.dataTask(with: URL(string: "https://apps.scaquarium.org/wp-json/wp/v2/gotspeciesid")!, completionHandler: { data, response, error in
guard let data = data else {
print("Something went wrong!")
return
}
var result: [Response]?
do {
result = try JSONDecoder().decode([Response].self, from: data)
}
catch { print(error) }
guard let json = result else {
return
}
//--All works and prints out nicely when I create a instance of getData() on my viewcontroller.
print(json[0].acf.common_name)
print(json[0].acf.scientific_name)
print(json[0].acf.size)
print(json[0].acf.fun_fact)
print(json[0].acf.conservation_status)
print(json[0].acf.species_image_1)
print(json[0].acf.species_image_2)
})
task.resume()
}
//------------END OF FETCH----------------------