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

SOLVED: Day 49 - Sending and receiving Codable data. Problem with decoder.decode(from)

Forums > 100 Days of SwiftUI

I noticed URLSession retrieves data but it can't be decoded in Response. (The url is correct)

URLSession.shared.dataTask(with: request) { data, response, error in
  if let data = data {
      let decoder = JSONDecoder()
      print(data)
      if let decodedResponse = try? decoder.decode(Response.self, from: data) {
          DispatchQueue.main.async {
              results = decodedResponse.results
          }
          return
      }
  }
  print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()

struct Result: Codable {
    var trackID: Int
    var trackName: String
    var collectionName: String
}
struct Response: Codable {
    var results: [Result]
}

2      

Replace this:

      if let decodedResponse = try? decoder.decode(Response.self, from: data) {
          DispatchQueue.main.async {
              results = decodedResponse.results
          }
          return
      }

with this:

do {
    let decodedResponse = try decoder.decode(Response.self, from: data)
    DispatchQueue.main.async {
        results = decodedResponse.results
    }
    return
} catch {
    print(error)
}

and see what error you get. Using try? masks any error by converting the response to an Optional.

2      

Thanks a lot, it seems I mispelled the trackId variable.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.