Firebase Server Timestamp to Double iOS

霸气de小男生 提交于 2021-01-27 18:29:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!