Firebase会移除不再属于查询的子级

时间:2017-07-30 17:52:28

标签: swift firebase-realtime-database

我过去常常使用observe调用.value,这会在查询中加载所有子项。实时地,当孩子不再是查询的一部分(即,其时间戳太旧)时,.value事件将被触发,并且将从我的应用中移除孩子的数据。出于性能目的,我不会使用observe调用.value,而是单独观察.childAdded.childChanged.childRemoved事件。但是,当子项不再是查询的一部分时,这些事件都不会被触发,并且子项的数据仍保留在我的应用程序中。我曾尝试过观察.childMoved,但也没有被解雇。如何复制观察.value的这一方面?这是代表我的一些代码:

class ViewController: UIViewController {

    var children_query: DatabaseQuery!
    var current_time: TimeInterval {
        return Date().timeIntervalSince1970
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.children_query = Database.database().reference().child("children").queryOrdered(byChild: "timestamp").queryStarting(atValue: current_time)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // refresh query every time this view appears (this is the root view controller so it comes and goes)
        self.children_query = Database.database().reference().child("children").queryOrdered(byChild: "timestamp").queryStarting(atValue: current_time)

        self.children_query.observe(.childAdded, with: { snapshot in
            print(snapshot.value)
        })

        self.children_query.observe(.childChanged, with: { snapshot in
            print(snapshot.value)
        })

        self.children_query.observe(.childRemoved, with: { snapshot in
            print(snapshot.value)
        })

        self.children_query.observe(.childMoved, with: { snapshot in
            print(snapshot.value)
        })
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.children_query.removeAllObservers()
    }
}

1 个答案:

答案 0 :(得分:0)

在这种情况下,我能为您提供简便的解决方案。只需将直接父级添加到所有值即可。

<!doctype html>
<html lang="en">
<head>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script>
  $(document).ready(function (){   
    var name = 'Juan';
    var pass = '123456';    
    $('#boton').click( function () {
      if ($('#name').val() === name && $('#pass').val() === pass ) {
          window.open('https://www.google.com/');
      } else {
          alert("WRONG PASSWORD");
      }
    });
  });
  </script>
</head>
<body>
<input type="text" id="name" placeholder="Username"> <br />
<input type="text" id="pass" placeholder="Password">
<button id="boton">Click Here</button>
</body>
</html>

现在,不是观察每个值,而是观察他们的直接父母。这样,根据rootNode: [ { your first value } { your second value } .... /* you can add value here */ {your last value } ] 内部更改的定义,它会触发dataSnapshot函数。