I have been having trouble trying to download a JSON file and return an array of objects for use in all parts of my viewcontroller. I found multiple solutions on StackOverflow which cited this current method as the solution for my data disappearing when I try to access the array contents anywhere else in the class but it doesn't appear to be working. I've tried maybe returning the data as an array within the method but can't quite figure it out.
Here's the method that first returns the JSON data as an array when the Datatask request is complete.
func LoadJSONFile(from url: String, completion: @escaping ([[String: Any]])->()) {
if let url = URL(string: url) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error == nil {
if let data = data {
do {
let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
if let content = json as? [[String: Any]] { // array of dictionaries
completion(content)
}
} catch {
// error while decoding JSON
print(error.localizedDescription)
}
} else {
print("Error: no data")
}
} else {
// network-related error
print(error!.localizedDescription)
}
}.resume()
}
}
This is an exact copy of the solution offered in this question : Answer
Here is my method which tries to return the finished/filled array:
func fillFromFile() -> [Asset_Content]{
let url = "URLSTRING"
var arry = [Asset_Content]()
LoadJSONFile(from: url, completion: { (result) in
for json in result {
let category = json["BIGCATEGORY"] as? String
let diagnosis = json["DIAGNOSIS"] as? String
let perspective = json["PERSPECTIVE"] as? String
let name = json["NAME"] as? String
let title = json["Title"] as? String
let UnparsedTags = json["TAGS"] as? String
let filename = json["FILENAME"] as? String
let tagArray = UnparsedTags?.characters.split(separator: ",")
for tag in tagArray!{
if(self.ListOfTags.contains(String(tag))){
//Do Nothing
}else{
self.ListOfTags.append(String(tag))
}
}
let asset = Asset_Content(category!, diagnosis!, perspective!, name!, title!, filename!)
arry.append(asset)
print("OLDCOUNT ==" , arry.count)
}
})
print("return count ", arry.count)
return arry
}