I have data that I get from a server and parse this data with JSON. So I have a URL session. This data gets parsed correctly, because I use a struct for it which is identical to the keys in the received dictionary, but the problem is that when I 'convert' this data into this object, I'm not able to store this object in an array outside of the scope of the completion handler.
The function used:
fileprivate func loadColor(_ urlString: URL?, completionHandler: @escaping (Color) -> Void) {
if let url = urlString {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error)
} else {
do {
if let data = data,
let color = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
guard let color2 = Color(json: color) else
{
fatalError("something didn't go as planned")
}
completionHandler(color2)
}
} catch {
print("Error deserializing JSON: \(error)")
}
}
}
task.resume()
}
}
I called this method in viewDidLoad() and try to get it into a array like this:
var colors : [Color] = []
override func viewDidLoad() {
super.viewDidLoad()
loadColor(URL(string: "API command here"), completionHandler: { color in
self.colors.append(color)
print("\(self.colors.count)")
})
print("\(self.colors.count)")
}
When I perform append on the colors array it does add it to the array because when printing the count it goes from 0 to 1, but when I go outside of the scope of this completion handler the array is empty again. What am I missing?