class DownloadingJSONViewModel: ObservableObject {
@Published var jaskiers: [Jaskier] = []
func getJaskiers() async {
guard let downloadedJaskiers = await downloadJaskiers() else { return }
self.jaskiers = downloadedJaskiers
}
func downloadJaskiers() async -> [Jaskier]? {,
let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
let (data, _) = try await URLSession.shared.data(for: request)
let decodedData = try decoder.decode([Jaskier].self, from: data)
return decodedData
} catch {
print("Invalid data")
print("Check out failed: (error.localizedDescription)")
}
return nil;
}}
struct DownloadingJSONBootcamp: View {
@StateObject var vm: DownloadingJSONViewModel = DownloadingJSONViewModel()
var body: some View {
ScrollView {
List {
ForEach(vm.jaskiers) { jaskier in
// ❗️ I can't read these on the screen
Text(jaskier.name)
Text(jaskier.address) etc.
}
}
}
.task {
await vm.getJaskiers()
// ✅ I can read this
print(vm.jaskiers[4].address)
}
}}
I’m trying to download a file in JSON format using SwiftUI and Codable.
The download is successful.
✅ I can read the downloaded data on the console,
❗️ but I cant read it onthescreen.
I think the problem may be in async/await things.
I have two async functions. Should I get rid of someone? I can not understand.
❓ What do I need to fix?