'Swift, Combine getting error after trying to download array of model type data when I have resolved all JSON fields from it
Error message: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "countries", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "countries", intValue: nil) ("countries").", underlyingError: nil)) Models:
struct ResponseModel: Codable {
let countries: [CountryModel]
}
struct CountryModel: Codable, Identifiable {
let countryName: String?
let uuid: String?
let totalHolidays: Int?
let iso: String?
var id: String {
return uuid ?? UUID().uuidString
}
enum CodingKeys: String, CodingKey {
case countryName = "country_name"
case iso = "iso-3166"
case totalHolidays, uuid
}
}
Service:
class CountryDataService: ObservableObject {
@Published var allCountries = ResponseModel(countries: [CountryModel]())
var countriesSubscription: AnyCancellable?
init() {
getCountries()
}
func getCountries() {
guard let url = URL(string: "https://calendarific.com/api/v2/countries?api_key=\(K.apiKey)") else { return }
countriesSubscription = NetworkingManager.download(url: url)
.decode(type: ResponseModel.self, decoder: JSONDecoder())
.sink(receiveCompletion: NetworkingManager.handleCompletion, receiveValue: { [weak self] (returnedCountries) in
self?.allCountries = returnedCountries
self?.countriesSubscription?.cancel()
})
}
}
Piece of json data:
{
"meta": {
"code": 200
},
"response": {
"url": "https://calendarific.com/supported-countries",
"countries": [
{
"country_name": "Afghanistan",
"iso-3166": "AF",
"total_holidays": 24,
"supported_languages": 2,
"uuid": "f0357a3f154bc2ffe2bff55055457068"
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
