With the code below, JSON data is parsed and is stored in the variable data
in the .onAppear
function, however an empty set of data is passed to the Content
view. How can that be fixed so that the JSON data passes to the DataView?
struct ContentView: View {
@State var data: [Data]
@State var index: Int = 0
var body: some View {
VStack {
DataView(data: data[index])
}
.onAppear {
let filePath = Bundle.main.path(forResource: "data", ofType: "json")
let url = URL(fileURLWithPath: filePath!)
data = getData(url: url)
}
}
func getData(url: URL) -> [Data] {
do {
let data = try Data(contentsOf: url)
let jsonDecoded = try JSONDecoder().decode([Data].self, from: data)
return jsonDecoded
} catch let error as NSError {
print("Fail: \(error.localizedDescription)")
} catch {
print("Fail: \(error)")
}
return []
}
}