WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Answered: Project 10-Sending and Receiving Codable Data

Forums > 100 Days of SwiftUI

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()
    }
}

   

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.