All I want to do is set a Firebase Server Timestamp in setData()
but I can’t seem to figure out how to get it to work.
Here is what I’ve tried:
for document in snapshot!.documents {
do {
try document.reference.collection("Data").document()
.setData(from: ["first" : FieldValue.serverTimestamp(), "second" : dataStringArray])
print("Data successfully written to firestore.")
} catch let error {
print("Error writing data to firestore: (error)")
}
}
The intent is to set a serverTimestamp as a field everytime the data is written to get a history of data writes.
It keeps showing the error Type of expression is ambiguous without more context
so I try to give it some context by casting it to FieldValue
but then I get the same ambiguous without more context
issue so I try to cast it to ServerTimestamp
or Timestamp
and I get Cannot convert value of type 'FieldValue' to type 'Timestamp' in coercion
.
It works well in Android to simply do this:
document.reference.collection("Data").document().set(FieldValue.serverTimestamp() to formattedDataList)
but for some reason it doesn’t work in Swift. I’ve been searching for hours now trying to understand this issue but haven’t been able to find a good explanation.
I also tried this:
setData(from: [FieldValue.serverTimestamp() : dataStringArray])
but I get Error writing data to firestore: invalidValue([<FSTServerTimestampFieldValue: 0x280412de0>:
2
Answers
The issue was I was using
setData(from:)
instead of simply usingsetData()
Changing this
.setData(from: ["first" : FieldValue.serverTimestamp(), "second" : dataStringArray])
to this
.setData(["first" : FieldValue.serverTimestamp(), "second" : dataStringArray])
totally fixed my problem.
It appears that I was trying to use an extension intended to simplify crafting custom objects but it wasn't added to the docs for some reason. I was using it wrong because I was trying to use it like what is in the docs.
This StackOverflow Question explains a bit more about the issue. Error when trying to call setData(from: ) in the Cloud Firestore ios API. How can i fix it?
Actually I wanted to write a comment, but due to the limitation not to be able to add code snippets, it became an answer. Please forgive me if it isn’t really the answer for you.
In the chat within my app I am using Date as a sendDate (see example from my code below), wouldn’t that an option for you?
Best, Sebastian