I can not pars data from fixtures array, every time I get a mistake
error in console log:
downloaded
Error info: typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [LiveZscores.EventsFull.(CodingKeys in _B768B663C3B4834FEE8438F5C59CA80A).fixtures, Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), LiveZscores.EventsData.(CodingKeys in _B768B663C3B4834FEE8438F5C59CA80A).result], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))
My code:
ViewController.swift
final let url = URL(string: "http://api.football-data.org/v1/fixtures")
override func viewDidLoad() {
super.viewDidLoad()
downloadJson()
}
func downloadJson() {
guard let downloadURL = url else { return }
URLSession.shared.dataTask(with: downloadURL) { (data, urlResponse, error) in
guard let data = data, error == nil, urlResponse != nil else {
print ("something")
return
}
print ("downloaded")
do {
let decoder = JSONDecoder()
let events = try decoder.decode(EventsFull.self, from: data)
print (events.fixtures)
}catch {
print("Error info: \(error)")
}
}.resume()
}
Events.swift
class EventsFull: Codable {
let fixtures: [EventsData]
init(fixtures: [EventsData]) {
self.fixtures = fixtures
}
}
class EventsData: Codable {
let date: String
let status: String
let matchday: Int
let homeTeamName: String
let awayTeamName: String
let result: String
let odds: Double
init(date: String, status: String, matchday: Int, homeTeamName: String, awayTeamName: String, result: String, odds: Double) {
self.date = date
self.status = status
self.matchday = matchday
self.homeTeamName = homeTeamName
self.awayTeamName = awayTeamName
self.result = result
self.odds = odds
}
}
"result": {"goalsHomeTeam": null,"goalsAwayTeam": null}. That's a Dictionary, but you wrotelet result: String.resultshould be a Dictionary, not a String, that's why you get an error. - Larme"result": {"goalsHomeTeam": 2,"goalsAwayTeam": 2,"halfTime":{"goalsHomeTeam": 1,"goalsAwayTeam": 0}. So I'd suggest to review yourresultand maybe create a new class from it (or if you are just interested in the final score, just read the 2 values, not thehalfTimeone). - Larme