Fix crash when decoding responses from Mastodon 3.4.0rc1 due to

differing date formats
This commit is contained in:
Shadowfacts 2021-05-09 21:49:16 -04:00
parent 21e4828a72
commit 8386e9d3c6
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
1 changed files with 15 additions and 1 deletions

View File

@ -28,11 +28,25 @@ public class Client {
static let decoder: JSONDecoder = { static let decoder: JSONDecoder = {
let decoder = JSONDecoder() let decoder = JSONDecoder()
let formatter = DateFormatter() let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZ" formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZ"
formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.locale = Locale(identifier: "en_US_POSIX") 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 return decoder
}() }()