问题
ServerValue.timestamp()
returns [AnyHashable : Any]
. How to convert it to Double
, so I could create a date with the timestamp.
回答1:
That's not exactly how the Firebase timestamp works.
What it actually does is writes a timestamp to a node but you don't have access to it until after the write.
To get access to it, attach an observer to that node so when the timestamp is written, it will be returned in a snapshot.
So first we define a var
let kFirebaseServerValueTimestamp = [".sv":"timestamp"]
then attach an observer to a node so when the timestamp is written, we are notified of the event
func attachObserver() {
let timestampRef = self.ref.child("timestamp")
timestampRef.observe(.value, with: { snapshot in
if snapshot.exists() {
let ts = snapshot.value as! //Int? Double? String?
print(ts)
}
})
}
and the function that writes out the timestamp, causing the above observer to receive the event
func doTimestamp() {
let timestampRef = self.ref.child("timestamp")
timestampRef.setValue(kFirebaseServerValueTimestamp)
}
Hope that helps - if more info is needed, post a comment.
来源:https://stackoverflow.com/questions/44527008/firebase-server-timestamp-to-double-ios