2016-11-13 34 views
1

我有一個帶回用戶標識或keys的GeoFire查詢。我順序回到keys,但我得到了幾個序列。我怎樣才能得到最後更新的序列?如何使用Swift使用Firebase GeoFire查詢多個鍵?

@IBAction func friendsNearMeACTN(sender: AnyObject) 
    { 
     let geofireRef = self.ref.child("UserLocations") 
     let geoFire = GeoFire(firebaseRef: geofireRef) 
     let circleQuery = geoFire.queryAtLocation(self.location, withRadius: 20.6) 
     circleQuery.observeEventType(.KeyEntered, withBlock: { (key: String!, location: CLLocation!) in 
      self.localUsers.append(key) 
      self.getLocalUsers() 
     }) 
    } 

func getLocalUsers() 
{ 
    print(self.localUsers) 

} 

這是我從func getLocalUsers()找回....

["WGueYzDjH4NW2vneHOyGmjf6PYB3"] 
["WGueYzDjH4NW2vneHOyGmjf6PYB3", "Cg4pQj36ttNUuWNqtc16tIFmI0A2"] 
["WGueYzDjH4NW2vneHOyGmjf6PYB3", "Cg4pQj36ttNUuWNqtc16tIFmI0A2", "N5pgqGEhW2f7PGGVmB3AQ8v1uPk2"] 

我怎麼能簡單地得到最後的陣列?

回答

0

這裏的問題在於,每次觀察者塊被觸發時,都會調用getLocalUsers func。你爲每一個結果調用它。您需要對結果進行計數,並在每次執行觀察程序塊時將計數值加1。當您的計數達到結果計數時,請調用getLocalUsers函數一次而不是三次。嘗試下面的代碼。我沒有測試過它。

@IBAction func friendsNearMeACTN(sender: AnyObject){ 
    var i = 0//The counter 
    let geofireRef = self.ref.child("UserLocations") 
    let geoFire = GeoFire(firebaseRef: geofireRef) 
    let circleQuery = geoFire.queryAtLocation(self.location, withRadius: 20.6) 
    circleQuery.observeEventType(.KeyEntered, withBlock: { (key: String!, location: CLLocation!) in 
     self.localUsers.append(key) 
     i += 1//Add one to i every time observer fires 
     if i == self.key.count {//if counter (i) is equal to the keys returned call getLocalUsers func once 
      self.getLocalUsers() 
     } 
    }) 
} 

func getLocalUsers(){ 
    print(self.localUsers) 
} 
1

的答案是GeoFire查詢是一個連續的異步調用,並需要最終代碼observeReadyWithBlock只喂self.localUsers()所收集的信息。這裏是例子...

let regionQuery = geoFire.queryWithRegion(self.region) 
     regionQuery.observeEventType(.KeyEntered, withBlock: { (key: String!, location: CLLocation!) in 
      var users = [String]() 
      users.append(key) 
      for keys in users 
      { 
       let user = keys 
       allKeys.append(user) 
      } 
      self.localUsers = allKeys 
      self.getLocalUsers() 
     }) 

     regionQuery.observeReadyWithBlock({() -> Void in 
      self.getLocalUsers() 
     }) 
相關問題