UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.