2016-04-18 15 views
0

我想为我的swift iOS应用程序在Firebase中创建一个查询。我在查询中遇到的问题是,它不会立即从Firebase获取坐标,除非它们被更改。我尝试了其他观察者类型,但都没有出现。我知道我目前有观察者类型需要更改,但我需要正确的方法,让应用程序加载后立即获取位置,并使用Firebase进行更新。 .childAdded立即获取位置,但在Firebase上更改时不会更新。我如何才能在Firebase中的现有和新生儿中获得结果?

userDirectory.queryOrderedByChild("receiveJobRequest") 
      .queryEqualToValue(1) 
      .observeEventType(.ChildChanged , withBlock: {snapshot in 
     var cIhelperslatitude = snapshot.value["currentLatitude"] 
     var cIhelperslongitude = snapshot.value["currentLongitude"] 

回答

1

如果您想要侦听多个事件类型,您需要注册多个侦听器。

let query = userDirectory.queryOrderedByChild("receiveJobRequest") 
         .queryEqualToValue(1) 

query.observeEventType(.ChildAdded, withBlock: {snapshot in 
    var cIhelperslatitude = snapshot.value["currentLatitude"] 
    var cIhelperslongitude = snapshot.value["currentLongitude"] 

query.observeEventType(.ChildChanged, withBlock: {snapshot in 
    var cIhelperslatitude = snapshot.value["currentLatitude"] 
    var cIhelperslongitude = snapshot.value["currentLongitude"] 

您可能需要重构的是普通代码的方法,你从他们的.ChildAdded.ChildChanged块调用。

或者,您可以注册一个.Value事件,每当查询中的值发生更改时,会触发初始值。但由于.Value与所有匹配的儿童调用,你必须然后循环遍历您的块中的孩子:

query.observeEventType(.Value, withBlock: {allsnapshot in 
    for snapshot in allsnapshot.children { 
     var cIhelperslatitude = snapshot.value["currentLatitude"] 
     var cIhelperslongitude = snapshot.value["currentLongitude"] 
    } 
+2

那应该是要query.observeEventType(*值*在答案的第二部分。 ? – Jay

+0

好的。固定! –

相关问题