I'm having a hard Time changing an my global array monthlyAvgArray through my parseJson() function. When I run the debugger, it shows that it has values at one point, but then when I try to access it outside the function, it says its empty. I have tried returning an array from my function and setting it equal to the global array, but that didn't work either.
Here is my global array:
//declaring the dynamic arrays that will hold the information that is parsed
//will be using the same two arrays for each plant
var dateArray = [String]()
var monthlyAvgArray = [Double]()
And here is my parseJson() that takes in a String for the URL.
func parseJson(URL_String:String) {
let url = URL(string: EBR_String)
//var monthlyDoubleArray = [Double]()
// Load the URL
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
// If there are any errors don't try to parse it, show the error
guard let data = data, error == nil else { print(error!); return }
let decoder = JSONDecoder()
do{
let plantData = try decoder.decode([Plant].self, from: data)
//get each plant dictionary in plantData array of plant dictionaries
for var eachPlant in plantData {
// check to see if any values of the 30 day avg are null
if (eachPlant.monthlyAVG == nil)
{
//set null values to
eachPlant.monthlyAVG = "0"
}
//print(eachPlant.date)
// print(eachPlant.monthlyAVG!)
let monthlyDouble = NSString(string: eachPlant.monthlyAVG!).doubleValue
let monthlyDouble2 = Double(round(100*monthlyDouble)/100)
// monthlyDoubleArray.append(monthlyDouble2)
self.monthlyAvgArray.append(monthlyDouble2)
//self.dateArray.append(eachPlant.date)
//print(monthlyDouble)
}
// at this point my array has values
print(self.monthlyAvgArray)
//print(self.dateArray)
}
catch let err{print(err)}
}).resume()
//at this point my array does not have values
print(monthlyAvgArray)
}
And I'm calling my parseJson() function in the viewDidLoad() here:
override func viewDidLoad() {
super.viewDidLoad()
//Initiatte calling the items download
// parseJson(URL_String: EBR_String)
parseJson(URL_String: EBR_String)
SetGraph ()
}
I did have the global arrays set to private earlier because I don't want them to be access in other View Controllers, but I do want to be be able to be access anywhere in this specific View Controller. I'm just wondering why I'm getting values in the array at one point, and then nothing afterwards. Can anyone help me out? Thanks.