From 8386e9d3c653a5fa8b4aed3ca81b0379838402a7 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Sun, 9 May 2021 21:49:16 -0400 Subject: [PATCH] Fix crash when decoding responses from Mastodon 3.4.0rc1 due to differing date formats --- Pachyderm/Client.swift | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Pachyderm/Client.swift b/Pachyderm/Client.swift index 9d16a895..21668cb0 100644 --- a/Pachyderm/Client.swift +++ b/Pachyderm/Client.swift @@ -28,11 +28,25 @@ public class Client { static let decoder: JSONDecoder = { let decoder = JSONDecoder() + let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZ" formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.locale = Locale(identifier: "en_US_POSIX") - decoder.dateDecodingStrategy = .formatted(formatter) + let iso8601 = ISO8601DateFormatter() + decoder.dateDecodingStrategy = .custom({ (decoder) in + let container = try decoder.singleValueContainer() + let str = try container.decode(String.self) + // for the next time mastodon accidentally changes date formats >.> + if let date = formatter.date(from: str) { + return date + } else if let date = iso8601.date(from: str) { + return date + } else { + throw DecodingError.typeMismatch(Date.self, .init(codingPath: container.codingPath, debugDescription: "unexpected date format")) + } + }) + return decoder }()