Hello,
I am trying to parse JSON data from github using a static function and therefore need my getRemoteFabricData function to return the parsed data. I know how to do this with local data but I can’t seem to get the data out of my session.dataTask object. My fabricData variable is marked as out of scope.
Any help would be appreciated, thanks!
static func getRemoteFabricData() -> [Fabric] {
// String path
let urlString = "https://asilena.github.io/ADCData/fabricData.json"
// Create url object
let url = URL(string: urlString)
guard url != nil else {
// Couldn't create url
return []
}
// Create a url request object
let request = URLRequest(url: url!)
// Get the session and kick off the task
let session = URLSession.shared
let dataTask = session.dataTask(with: request) { data, response, error in
// Check if there is an error
guard error == nil else {
//There was an error
return
}
// Create json decoder
let decoder = JSONDecoder()
do{
// Decode
let fabricData = try decoder.decode([Fabric].self, from: data!)
// Add the unique IDs
for f in fabricData {
f.id = UUID()
}
}
catch {
// Error with parsing JSON
print(error)
}
}
// Kick off the data task
dataTask.resume()
return fabricData
}