Covid19StatsWidgetKit icon indicating copy to clipboard operation
Covid19StatsWidgetKit copied to clipboard

Date fix covid api

Open philipp65 opened this issue 4 years ago • 1 comments

fixes date conversion bug

philipp65 avatar Feb 03 '21 10:02 philipp65

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
    }()

crazygit avatar Nov 23 '22 04:11 crazygit