I have a @State var tripDate = Date()
I want to add to firestore db
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
}
}
}
and also get data from firestore
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
}
}
}
this is the button to add
Button(action: {
Eventmodel.addData(tripDate: tripDate)
}) {
Text("Submit")
}
any idea how can I covert the date in these cases to timestamp (in these functions) since Firestore doesn't take Date it rather takes timestamps and incase I remain putting it as a date, fatal error occurs and the app crashed and freezes , any idea thank you alot !
CodePudding user response:
You can convert Date
into a timestamp by using its timeIntervalSince1970
property. If the API you're using supports floating point numbers, you can use it as is, or just convert it to a String
. An alternative could be using a DateFormatter
.
CodePudding user response:
It looks like the Swift Firebase library has a class Timestamp
with an initializer that takes a Date
:
convenience init(date: Date)
And has a function that will convert a Timestamp
to a Date
:
func dateValue() -> Date
You could also calculate seconds and nanoseconds from a Date manually. That might look something like this:
extension Date {
var secondsAndNanoseconds: (Int, Int) {
let result = timeIntervalSince1970
let seconds = Int(result)
return (seconds, 1000000000 * (result-seconds)
}
}