For those curious, I was able to work this out myself...
I had placed the List modifier
.task {
await loadData()
}
in the wrong location. Once placed correctly on the List, the receipt of codable data was successful.
==================================================================================
I'm working on Project 10 and currently reviewing the section titled "Sending and receiving Codable data with URLSession and SwiftUI". The section builds a program to fetch some song data from itunes.
I have reviewed the lesson and built the app per Paul's instructions. The app builds successfully but I get no results from iTunes, i.e., no list of trackName and collectionName appear in the Simulator. It just sits there blank.
Any thoughts why I am not receiving the data from iTunes? Code follows...
Thanks.
import SwiftUI
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
var trackId: Int
var trackName: String
var collectionName: String
}
struct ContentView: View {
@State private var results = [Result]()
func loadData() async {
guard let url = URL(string: "https://itunes.apple.com/search? term=taylor+swift&entity=song&limit=25") else {
print("Invalid URL")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
results = decodedResponse.results
}
} catch {
print("Invalid data")
}
}
var body: some View {
List(results, id: \.trackId) { item in
VStack(alignment: .leading) {
Text(item.trackName)
.font(.headline)
Text(item.collectionName)
}
.task {
await loadData()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}