如何在swift中创建负的Firebase时间戳 [英] How to create negative Firebase timestamp in swift

查看:159
本文介绍了如何在swift中创建负的Firebase时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在使用的iOS应用程序,我需要按降序获取消息,即最新的消息是第一个,然后是第二个最新的消息等。



从看着其他SO的答案和研究似乎我的情况最好的办法是创建一个负面的时间戳,然后坚持到数据库作为消息的额外属性。然后我用 queryOrderedByChild('negativeTimestamp')来获取中的消息。 $ b> observeSingleEvent ,然后有一个childAdded观察者来处理初始调用时发送的消息。



在firebase documentation 它说我可以从这段代码中获取服务器时间戳值 firebase.database.ServerValue.TIMESTAMP



我如何为Swift 3编写这个代码?



如果您想让Firebase生成一个时间戳记,那么也可以这个小小的活泼的Firebase结构和一段代码。

首先,让我们来看看这个结构

  root 
parent_node
-Y8j8a8jsjd0adas
time_stamp:-1492030228007
timestamp:1492030228007

接下来,创建和使用该结构的一些代码:

定义一个我们可以在我们的类中使用的var引用Firebase时间戳记

  let kFirebaseServerValueTimestamp = [.sv:timestamp] 

以及一个将观察者添加到timestamp节点的函数:

<$ p $ func attachObserver(){

let timestampRef = self.ref.child(timestamp)
let parentNodeRef = self.ref.child(paren ()。
var count = 0

timestampRef.observe(.value,with:{snapshot in

如果snapshot.exists(){
计数+ = 1
如果计数> 1 {
让ts = snapshot.value as! Int
let neg_ts = -ts
let childNodeRef = parentNodeRef.childByAutoId()
let childRef = childNodeRef.child(time_stamp)
childRef.setValue(neg_ts)
count = 0
}
}
})

一个写出时间戳的函数,因此会导致观察者触发,这会根据Firebase时间戳在父节点内创建子节点。

  func doTimestamp(){
let timestampRef = self.ref.child(timestamp)
timestampRef.setValue(kFirebaseServerValueTimestamp)
}

下面是这个概要。



在attachObserver函数中,我们附加一个观察者到时间戳节点 - 该节点可能存在,也可能不存在,但是如果不存在,将会创建 - 继续阅读。当时间戳记节点发生事件时,闭包中的代码被调用。
$ b 当调用doTimestamp函数时,会创建时间戳记并写入时间戳记节点,然后触发我们在attachObserver中附加的观察者。

观察闭包中的代码执行以下操作:

确保快照包含一些东西,如果是的话,增加一个计数器(更多的一点)。如果计数器大于1,则从快照中以整数形式获取时间戳。然后,创建它为负数,并将其作为parent_node的子节点写回Firebase。



如果您希望使用Firebase为子节点添加时间戳生成的时间戳,但反向加载/排序负值 - 这与OP问题有关。



这里发生的情况是,当发生这种情况时

  timestampRef.setValue(kFirebaseServerValueTimestamp)

它实际上会向节点写入两次,这会导致更近的代码被调用两次。

也许Firebaser可以解释这一点,但我们需要忽略第一个事件并捕获第二个,这是实际的时间戳。

因此,第一个事件将导致观察员更接近火灾,使计数= 1,这将被忽略,由于if语句。

然后第二个事件触发,其中包含实际的时间戳,这就是我们用来做负面和写Firebase。



希望这可以帮助OP和评论者。


For an iOS app I am working on, I need to fetch messages in descending order i.e the latest message comes first, followed by second newest message etc.

From looking at other SO answers and research it seems that the best approach for my situation is to create a negative timestamp and then persist that to the database as an extra property to messages.

I will then use queryOrderedByChild('negativeTimestamp') to fetch the messages in a observeSingleEvent and then have a childAdded observer to handle messages which are sent once initial calls are made.

In the firebase documentation it says I can get the server timestamp value from this snippet of code firebase.database.ServerValue.TIMESTAMP

How do I write this for Swift 3?

解决方案

First, see the linked answer in the comments. That answer relies on the client to generate a timestamp that's made negative and written to Firebase.

If you want to have Firebase generate a timestamp, that can be done as well with this little snappy Firebase structure and piece of code.

First, let's take a look at the structure

root
  parent_node
    -Y8j8a8jsjd0adas
       time_stamp: -1492030228007
  timestamp: 1492030228007

Next, some code to create and work with that structure:

Define a var we can use within our class that references the Firebase time stamp

let kFirebaseServerValueTimestamp = [".sv":"timestamp"]

and a function that adds an observer to the timestamp node:

func attachObserver() {

    let timestampRef = self.ref.child("timestamp")
    let parentNodeRef = self.ref.child("parent_node")
    var count = 0

    timestampRef.observe(.value, with: { snapshot in

        if snapshot.exists() {
            count += 1
            if count > 1 {
                let ts = snapshot.value as! Int
                let neg_ts = -ts
                let childNodeRef = parentNodeRef.childByAutoId()
                let childRef = childNodeRef.child("time_stamp")
                childRef.setValue(neg_ts)
                count = 0
            }
        }
    })

And a function that writes out a timestamp, therefore causing the observer to fire which creates child nodes within the parent_node based on the Firebase time stamp

func doTimestamp() {
    let timestampRef = self.ref.child("timestamp")
    timestampRef.setValue(kFirebaseServerValueTimestamp)
}

Here's the rundown.

In the attachObserver function, we attach an observer to the timestamp node - that node may or may not exist but if it doesn't it will be created - read on. The code in the closure is called any time an event occurs in the timestamp node.

When the doTimestamp function is called, it creates and writes a timestamp to the timestamp node, which then fires the observer we attached in attachObserver.

The code in the observe closure does the following:

Make sure the snapshot contains something, and if it does, increment a counter (more on that in a bit). If the counter is greater than 1 get the timestamp as an integer from the snapshot. Then, create it's negative and write it back out to Firebase as a child of parent_node.

How this would apply would be anytime you want to timestamp a child node with a Firebase generated timestamp but negative value for reverse loading/sorting - which speaks to the OP question.

The gotcha here is that when this happens

    timestampRef.setValue(kFirebaseServerValueTimestamp)

It actually writes twice to the node, which would cause the code in the closer to be called twice.

Maybe a Firebaser can explain that, but we need to ignore the first event and capture the second, which is the actual timestamp.

So the first event will cause the observer closer to fire, making count = 1, which will be ignored due to the if statement.

Then the second event fires, which contains the actual timestamp, and that's what we use to make negative and write out to Firebase.

Hope this helps the OP and the commenters.

这篇关于如何在swift中创建负的Firebase时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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