[英]Is it possible yet to use Decodable with Firestore Timestamps/Dates?
我有一個[String: Bookmark]
字典,但createdAt被保存為Timestamp
,並且解碼器在試圖理解Date
時拋出錯誤
***由於未捕獲的異常'NSInvalidArgumentException'而終止應用程序,原因:'JSON寫入中的類型無效(__NSDate)'
struct Bookmark: Decodable {
let messageId: String
let messageCreatedAt: Date
}
JSONDecoder().decode([String: Bookmark].self, data: data)
有沒有一種方法可以使Swift的Decodable
協議與Firestore Timestamps完美配合?
編輯:
如果我打印[String: Any]
,然后嘗試在控制台中像這樣解碼
▿ 1 : 2 elements
- key : "messageCreatedAt"
- value : 2018-11-27 20:59:11 +0000
po valueDict["messageCreatedAt"] as? Date
我懂了
▿ Optional<Date>
▿ some : 2018-11-27 20:59:11 +0000
- timeIntervalSinceReferenceDate : 565045151.531769
因此,它一定是“可Decodable
中無法識別和解析的東西嗎?
編輯:
JSON是
{
"messageId": "abc123",
"messageCreatedAt": "2018-11-27 20:59:11 +0000"
}
JSONDecoder
如何解碼日期由.dateDecodingStrategy
屬性的值定義。
如果必須從字符串中解析Date
,則應使用.iso8601
或.formatted(_:)
(或者,如果日期格式確實是自定義的,復雜和/或怪異的,則可以使用.custom(_:)
)。
您的日期字符串幾乎采用ISO 8601
格式(日期和時間部分之間僅缺少T
),但這足以失敗。
因此,這里最好的選擇是使用formatted(_:)
:
// Declare it somewhere and reuse single instance as much as possible, formatter initialization is quite expensive
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // Better to fix Locale here
dateFormatter.dateFormat = "yyyy-MM-dd kk:mm:ss Z"
接着
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let bookmark = try decoder.decode(Bookmark.self, from: data)
print(bookmark.messageCreatedAt, bookmark.messageCreatedAt.timeIntervalSince1970)
// prints "2018-11-27 20:59:11 +0000 1543352351.0"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.