I am trying to decode some JSON in swift, but I keep getting an error, which I am assuming is because my struct is not written correctly. Any ideas? I am calling this API https://pokeapi.co/api/v2/pokemon/1/
Here is the json decode call:
func fetchPokemonImages() {
for var pokemons in self.Pokemons {
let defaultSession = URLSession(configuration: .default)
if let url = URL(string: pokemons.url) {
let request = URLRequest(url: url)
let dataTask = defaultSession.dataTask(with: request) { (data, response, error) in
guard let pokemonImage = try? JSONDecoder().decode(PokemonImageList.self, from: data!) else {
print(error)
return
}
DispatchQueue.main.async {
self.PokemonsImage.append(contentsOf: pokemonImage.sprites)
self.PokemonTableView.reloadData() }
}
dataTask.resume()
}
}
}
Here are my structs:
struct PokemonImage: Codable {
let back_default: String
enum CodingKeys: String, CodingKey {
case backDefault = "back_default"
}
init(backDefault: String) {
self.backDefault = backDefault
}
init(from decoder: Decoder) throws {
let postsContainer = try decoder.container(keyedBy: CodingKeys.self)
backDefault = try postsContainer.decode(String.self, forKey: .backDefault)
}
}
struct PokemonImageList: Codable {
let sprites: [PokemonImage]
enum CodingKeys: String, CodingKey {
case sprites
}
}
try?instead oftry? Are you aware that the error you are printing when the decoding fails is the parameter to the closure so it has nothing to do with the decoding.