本文介绍了如何在Swift中将Firestore FieldValue解析为Date的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将文档存储在Cloud Firestore数据库的集合中.在此文档中,我想参考文档的存储时间,因此我正在使用Firestore的serverTimeStamp()函数的rel ="nofollow noreferrer"> FieldValue 对象.

I am storing a document within a collection in a Cloud Firestore database. In this document, I want a reference to when the document was stored so I am using Firestore's FieldValue object which has a serverTimeStamp() function.

我无法在客户端上将此FieldValue对象解析为Date/NSDateString.我花了一些时间阅读Firestore iOS文档,但找不到任何线索.

I am unable to parse this FieldValue object on the client as either a Date/NSDate or String. I have spent some time reading the Firestore iOS documentation and cannot find any leads on this.

从数据库到客户端获取FieldValue没有问题,但是,我无法将类型为FieldValue的timeStamp转换/转换为任何值.

There is no issue getting the FieldValue from the database to the client, however, I am unable to cast/convert the timeStamp of type FieldValue to anything.

尝试转换为字符串和日期:

Attempts to convert to string and date:

let timeStampString : String = message.timeStamp

let timeStampDate = Date(timeIntervalSince1970: message.timeStamp)

  • 无法将类型为FieldValue的值分配为类型为String
  • 无法将类型FieldValue的值转换为预期的参数类型TimeInterval(又名Double)
  • Cannot assign value of type FieldValue to type String
  • Cannot convert value of type FieldValue to expected argument type TimeInterval (aka Double)

查看道格·史蒂文森(Doug Stevenson)的答案后,处理此问题的最佳方法是在读取客户端信息时将timeStamp值转换为TimeStamp(而非FieldValue).

After reviewing Doug Stevenson's answer, the best way to handle this is by casting your timeStamp value to a TimeStamp (not FieldValue) when reading the info on the client.

let timeStamp = document["yourTimeStampKey"] as! TimeStamp

而不是

let timeStamp = document["yourTimeStampKey"] as! FieldValue

推荐答案

无需解析. Firestore时间戳字段的类型为时间戳,您应该直接使用.它表示一个具有纳秒精度的时间点.

There's no parsing needed. Firestore timestamp fields are of type Timestamp, which you should use directly. It represents a point in time with nanosecond precision.

代码:

let timeStamp = document["yourTimeStampKey"] as! TimeStamp

而不是

let timeStamp = document["yourTimeStampKey"] as! FieldValue

这篇关于如何在Swift中将Firestore FieldValue解析为Date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 10:27