无法从Firestore DocumentSnapshot中提取日期或时间戳

时间:2019-12-09 03:25:56

标签: swift firebase date google-cloud-firestore timestamp

我正在检索一组包含StringsDatesTimestamp的事件的文档。 Strings没问题,但是最近我在模型中添加了DatesTimestamp,尽管我可以在Firebase控制台中清楚地看到它们,但它们总是以nil返回,这是我设置为默认值。它们已正确存储。

用于DocumentSnapshot检索的初始设置

init?(snapshot:DocumentSnapshot){

    self.eventId = snapshot.get("eventId") as? String ?? "No event Id"
    self.byId = snapshot.get("byId") as? String ?? "No uid"
    self.adminUser = snapshot.get("adminUser") as? String ?? "No admin user"
    //self.eventCreated = snapshot.get("eventCreated") as? Timestamp ?? "No Event Created Date"
    self.eventName = snapshot.get("eventName") as? String ?? "No Event Name"
    self.eventLocation = snapshot.get("eventLocation") as? String ?? "No Location"
    self.eventStart = snapshot.get("eventStart") as? Date ?? nil
    self.eventEnd = snapshot.get("eventEnd") as? Date ?? nil

}

DocumentSnapshot的结果

adminUser: "", 
byId: "juYtTP509rhXYPd433", 
eventCreated: nil, //Timestamp retrieved as nil
eventId: "gC2RVdUuB9CD66JEYM18", 
eventName: "test", 
eventLocation: "", 
eventStart: nil, //Date retrieved as nil
eventEnd: nil, //Date retrieved as nil

事件模型

struct Event {

var adminUser = ""
var byId = ""
var eventCreated:Timestamp?
var eventId = ""
var eventName = ""
var eventLocation = ""
var eventStart:Date? = nil
var eventEnd:Date? =  Date(timeIntervalSince1970: 0)

This is the document in the Firebase console

请让我知道是否需要在此处添加该方法以获得更好的上下文?

1 个答案:

答案 0 :(得分:1)

Firestore没有内部日期类型。在内部,当它接收到日期或时间戳作为输入时,它将创建一个Timestamp,因此无论哪种情况(从没有日期),这都是您的代码应该从DocumentSnapshot中获得的代码。