I have a getJson function which I am using to parse json from a URLSession into an array of HouseDetails.
func getJson(completion: @escaping ([HouseDetails]?, Error?) -> Void) {
var result: [HouseDetails] = []
let jsonUrlString = "https://data.melbourne.vic.gov.au/resource/i8px-csib.json"
guard let url = URL(string: jsonUrlString)
else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
if let error = error {
DispatchQueue.main.async {
completion(nil, error)
}
return
}
do {
let houses = try JSONDecoder().decode([HouseDetails].self, from: data)
for h in houses {
result.append(h)
}
DispatchQueue.main.async {
completion(result, error)
}
}
catch let jsonErr {
print("Error with json serialization", jsonErr)
}
}.resume()
}
I then call this function from the main viewDidLoad() function here:
getJson { (x, error) in
guard let x = x, error == nil else {
return
}
hsArray = x
}
However, when I assign hsArray (which is a global array of [HouseDetails] to the answer, nothing gets added to it. Once again, if I loop through the "x" variable where I am calling getJson, I can see all the values are there. So I believe it is still an asynchronous issue. Thanks for any help.