2

ServerValue.timestamp() returns [AnyHashable : Any]. How to convert it to Double, so I could create a date with the timestamp.

lysov
  • 160
  • 2
  • 14

1 Answers1

0

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.

Jay
  • 34,438
  • 18
  • 52
  • 81
  • So the only way to get a serverstamp is firstly write it to the database, right? By the way your `doTimestamp()` function doesn' work. I used `func createTimestamp() { let timestampRef = self.ref.child("timestamp") timestampRef.setValue(ServerValue.timestamp()) }` – lysov Jun 14 '17 at 02:15
  • @lysov What doesn't work. That's code that's been copied and pasted from a functiontional app. You have to remember to define kFirebaseServerValueTimestamp, write that to the node, which then fires the observer so the timestamp can be read in and used. – Jay Jun 15 '17 at 22:03