尝试在 Swift 中将 Firebase 时间戳转换为 NSDate [英] Trying to convert Firebase timestamp to NSDate in Swift

查看:39
本文介绍了尝试在 Swift 中将 Firebase 时间戳转换为 NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Swift 应用中使用 Firebase 时间戳.我想将它们存储在我的 Firebase 中,并在我的应用中将它们用作本机 NSDate 对象.

I'm trying to use Firebase timestamps in a Swift app. I'd like to store them in my Firebase, and use them as native NSDate objects in my app.

文档说他们是unix时代,所以我试过了:

The docs say they are unix epoch time, so I've tried:

NSDate(timeIntervalSince1970:FirebaseServerValue.timestamp)

运气不好.

这个:

FirebaseServerValue.timestamp

返回

0x00000001199298a0

根据调试器.传递这些时间戳的最佳方法是什么?

according to the debugger. What is the best way to pass these timestamps around?

推荐答案

ServerValue.timestamp() 与在 Firebase 中设置普通数据的工作方式略有不同.它实际上并不提供时间戳.相反,它提供了一个值,告诉 Firebase 服务器用时间填充该节点.通过使用此功能,您应用的时间戳将全部来自一个来源 Firebase,而不是用户的设备所说的任何内容.

ServerValue.timestamp() works a little differently than setting normal data in Firebase. It does not actually provide a timestamp. Instead, it provides a value which tells the Firebase server to fill in that node with the time. By using this, your app's timestamps will all come from one source, Firebase, instead of whatever the user's device happens to say.

当您(从观察者处)取回值时,您将获得自纪元以来的毫秒数.您需要将其转换为秒以创建 NSDate.下面是一段代码:

When you get the value back (from a observer), you'll get the time as milliseconds since the epoch. You'll need to convert it to seconds to create an NSDate. Here's a snippet of code:

let ref = Firebase(url: "<FIREBASE HERE>")

// Tell the server to set the current timestamp at this location.
ref.setValue(ServerValue.timestamp()) 

// Read the value at the given location. It will now have the time.
ref.observeEventType(.Value, withBlock: { 
    snap in
    if let t = snap.value as? NSTimeInterval {
        // Cast the value to an NSTimeInterval
        // and divide by 1000 to get seconds.
        println(NSDate(timeIntervalSince1970: t/1000))
    }
})

您可能会发现,您会收到两个时间戳非常接近的事件.这是因为 SDK 会在收到 Firebase 的回复之前对时间戳进行最佳猜测".一旦它从 Firebase 听到实际值,它就会再次引发 Value 事件.

You may find that you get two events raised with very close timestamps. This is because the SDK will take a best "guess" at the timestamp before it hears back from Firebase. Once it hears the actual value from Firebase, it will raise the Value event again.

这篇关于尝试在 Swift 中将 Firebase 时间戳转换为 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆