【问题标题】:How can I retrieve the data once in Firebase 3 and Swift 3 (Stopping observer)如何在 Firebase 3 和 Swift 3 中检索一次数据(停止观察者)
【发布时间】:2017-07-05 18:29:37
【问题描述】:

我在 angularjs 1.5 中使用 firebase 3 启动了我的 Web 应用程序。我现在想为我的 Web 应用程序创建一个 IOS 应用程序。该应用程序是一个时钟系统,用户可以在其中签入或签出他的工作时间。

为了简单起见,我喜欢 firebase 中的这张表:

worktimes
   -Kd4swkAQJTRjCbD0CCy
     + ----- IN  | '2017-02-16 10:00:00'
     + ----- OUT | '2017-02-16 13:00:00'

案例:

  • 如果用户有一个“OUT”值,创建一个新的工作时间。
  • 如果用户在“OUT”中没有值,例如 NULL,我想更新 “OUT”并设置当前时间戳。

在 JS 中,我的代码如下所示:

var database = firebase.database();
var ref = database.ref().child('worktimes')

查询(Javascript):

ref
   .startAt('2017-02-16 00:00:00')
   .endAt('2017-02-16 23:59:59')
   .orderByChild('timestamp')
   .limitToLast(1)
   .once('value', function(snapshot) { 
       // Getting data once here
})

查询(Swift 3):

ref
   .queryStarting(atValue: "2017-02-16 00:00:00")
   .queryEnding(atValue: "2017-02-16 23:59:59")
   .queryOrdered(byChild: "timestamp")
   .queryLimited(toLast: 1) // return only the latest entry
   .observe(FIRDataEventType.value, with: { (snapshot) in

      if !snapshot.value is NSNull {
         // work here with the data once

        for child in snapshot.children {
        // if I do an update here like this:

              let snap = child as! FIRDataSnapshot 
              let dict = snap.value as! [String: AnyObject] 

              let id = dict["id"] as! String
              let IN = dict["in"]
              let OUT = dict["out"]

              if(OUT  == nil){

        // UPDATE QUERY     
        // If I update here my Data, the query ends and starts again.

        ref.child("-Kd4swkAQJTRjCbD0CCy").updateChildValues(["timestamp" : "2017-02-"])

              } else {

           // creating new worktime here.. 
           }

         } // end of for

      } // end of if

   })

正如我在评论中所写(见更新查询后),快照最终结束,但它再次循环通过快照。我已经想通了,因为数据发生了变化,它再次触发了循环。

我试过了

ref.removeAllObservers()

移除观察者。它工作正常,但如果我在更新查询后尝试它不起作用。它创建了一个永不停止的循环。如何停止观察,我不需要检查新的更新。

提前致谢!

【问题讨论】:

    标签: swift firebase observers


    【解决方案1】:

    只需按照documentation 中的说明使用observeSingleEvent

    ref
       .queryStarting(atValue: "2017-02-16 00:00:00")
       .queryEnding(atValue: "2017-02-16 23:59:59")
       .queryOrdered(byChild: "timestamp")
       .queryLimited(toLast: 1) // return only the latest entry
       .observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in
           ...
    

    【讨论】:

    • 谢谢老兄!我已经尝试过observeSingleEvent,它没有用。但是我现在在您的评论中看到我错过了参数中的“of:”。现在可以了!
    猜你喜欢
    • 2017-12-24
    • 2018-04-23
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多