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

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

问题描述

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



文档说它们是unix时代,所以我尝试:

$ p $ NSDate(timeIntervalSince1970:FirebaseServerValue.timestamp)




<$ p $ FirebaseServerValue.timestamp

返回


$根据调试器,b $ b

  0x00000001199298a0 

什么是最好的方式来传递这些时间戳?

解决方案

ServerValue.timestamp()的工作方式与在Firebase中设置普通数据有所不同。它实际上并没有提供时间戳。而是提供一个告诉Firebase服务器随时间填充该节点的值。通过使用这个,你的应用程序的时间戳将全部来自一个来源,Firebase,而不是任何用户的设备碰巧说。



当你从观察者),你会得到从时代开始的毫秒数。您需要将其转换为秒来创建一个NSDate。以下是一段代码:

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

//告诉服务器在这个位置设置当前时间戳。
ref.setValue(ServerValue.timestamp())

//读取给定位置的值。现在有时间了。
ref.observeEventType(.Value,withBlock:{
snap in
if let t = snap.value as?NSTimeInterval {
//将值转换为NSTimeInterval $ b $
println(NSDate(timeIntervalSince1970:t / 1000))
}
})
pre>

您可能会发现您会收到两个非常接近时间戳的事件。这是因为在从Firebase收到回报之前,SDK会在时间戳上采取最好的猜测。一旦它听到Firebase的实际价值,它将再次提升Value事件。

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.

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

NSDate(timeIntervalSince1970:FirebaseServerValue.timestamp)

with no luck.

This:

FirebaseServerValue.timestamp

returns

0x00000001199298a0

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

解决方案

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.

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))
    }
})

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天全站免登陆