Covid19StatsWidgetKit
Covid19StatsWidgetKit copied to clipboard
Date fix covid api
fixes date conversion bug
There are two different date format in API response now, WTF!🤣
In API /summary
2022-11-23T01:25:02.187Z
In API /total/country/<CountryID>
2020-01-22T00:00:00Z
change jsonDecoder
to below
static let jsonDecoder: JSONDecoder = {
let dateFormatterWithFractionalSeconds = DateFormatter()
dateFormatterWithFractionalSeconds.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let dateFormatterWithoutFractionalSeconds = DateFormatter()
dateFormatterWithoutFractionalSeconds.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
if let date = dateFormatterWithFractionalSeconds.date(from: dateString) {
return date
} else if let date = dateFormatterWithoutFractionalSeconds.date(from: dateString) {
return date
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "")
}
}
return decoder
}()