我有一个@State var tripDate = Date()
我想添加到消防仓库数据库
func addData(tripDate: Date) {
// Get a reference to the database
let db = Firestore.firestore()
// Add a document to a collection
db.collection("tripDate":tripDate]) { error in
// Check for errors
if error == nil {
// No errors
// Call get data to retrieve latest data
self.getData()
}
else {
// Handle the error
}
}
}
并从消防仓库获取数据
func getData() {
// Get a reference to the database
let db = Firestore.firestore()
// Read the documents at a specific path
db.collection("Event").getDocuments { snapshot, error in
// Check for errors
if error == nil {
// No errors
if let snapshot = snapshot {
// Update the list property in the main thread
DispatchQueue.main.async {
// Get all the documents and create Todos
self.list = snapshot.documents.map { d in
// Create a Todo item for each document returned
return Event(id: d.documentID,
tripDate: d["tripDate"] as! Date,
)
}
}
}
}
else {
// Handle the error
}
}
}
这是添加的按钮
Button(action: {
Eventmodel.addData(tripDate: tripDate)
}) {
Text("Submit")
}
我该如何将这些情况下的日期转换为时间戳(在这些函数中(,因为Firestore不采用日期,而是采用时间戳,如果我仍将其作为日期,则会发生致命错误,应用程序崩溃并冻结,谢谢!
您可以使用timeIntervalSince1970
属性将Date
转换为时间戳。如果您使用的API支持浮点数,您可以按原样使用它,也可以将其转换为String
。一种替代方案可以是使用CCD_ 5。
看起来Swift Firebase库有一个类Timestamp
,它带有一个初始化器,该初始化器接受Date
:
convenience init(date: Date)
并具有将Timestamp
转换为Date
:的功能
func dateValue() -> Date
您还可以手动计算Date的秒和纳秒。这可能看起来像这样:
extension Date {
var secondsAndNanoseconds: (seconds: Int, nanoseconds: Int) {
let result = timeIntervalSince1970
let seconds = Int(result)
return (seconds, Int(1000000000 * (result-Double(seconds))))
}
}