NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Day 49 Recieving Codable Data Issue...

Forums > 100 Days of SwiftUI

For some reason I am only getting an Unknown error message when running this code. I have tried debugging and it appears I am getting back data but decoding is apparently failing and I have no idea why. If anyone can help I would appreciate...

import SwiftUI

struct Response: Codable {
    var results: [Result]
}

struct Result: Codable {
    var trackID: Int
    var trackName: String
    var collectionName: String
}

struct SendingRecievingCodableDataSample: View {

    @State var results = [Result]()

    var body: some View {
        List(results, id: \.trackID) { item in
            VStack(alignment: .leading) {
                Text(item.trackName)
                    .font(.headline)
//                Text(item.collectionName)
            }//:VSTACK
        }//: LIST
        .onAppear(perform: loadData)
    }

    func loadData() {

     //: 1. Create URL we want to access

        guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else {
            print("Invalid URL")
            return
        }
        //: 2. Wrap that in a URLRequest

        let request = URLRequest(url: url)

        //: 3. Create and start networking task
        URLSession.shared.dataTask(with: request) { data, response, error in

            if let data = data {
                print("Data: \(data)")
                //: 4. Handle result of netwoking task
                if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
                    // we have good data – go back to the main thread
                    print ("DecodeResponse: \(decodedResponse)")

                    DispatchQueue.main.async {
                        // update our UI
                        self.results = decodedResponse.results
                        print ("Results: \(results)")

                    }

                    // everything is good, so we can exit
                    return
                }
            }

            // if we're still here it means there was a problem
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")

        }.resume()

    }
}

1      

Your keys are not correct. You have trackID but the JSON response has trackId. You either need to rename the key in your Result struct or use a CodingKeys enum to map the key names.

1      

Oh, and a (hopefully helpful) hint when decoding JSON:

Don't do this:

if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
...
}

because converting the return value of decode into an Optional masks any error that may occur.

Do this instead:

do {
    let decodedResponse = try JSONDecoder().decode(Response.self, from: data)
    ...
}
catch {
    print(error)
}

Once you get it working, you can go back to the other way but while developing you want to see the errors. (Also, don't print error.localizedDescription because it is less useful.)

1      

Thank you @roosterboy! Didn't see the key mismatch, and also thanks for the helpful tip on using a do catch block instead of the if let since I was not getting any useful error before.

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.