2017-07-19 48 views
2

我正在使用GeoFire並試圖只獲取滿足一些條件的3個結果。這是我的情況,它並不會阻止觀察者。有幾千個結果,我得到了它,但我只需要3.我基於this answer,但它不適用於我的情況,因爲你可以看到。 請有人幫忙嗎?GeoFire + Swift 3不能停止觀測

var newRefHandle: FIRDatabaseHandle? 
var gFCircleQuery: GFCircleQuery? 

func findFUsersInOnePath(location: CLLocation, 
         radius: Int, 
         indexPath: String, 
         completion: @escaping() ->()){ 
    var ids = 0 
    let geofireRef = usersRef.child(indexPath) 
    if let geoFire = GeoFire(firebaseRef: geofireRef) { 
     gFCircleQuery = geoFire.query(at: location, withRadius: Double(radius)) 
     newRefHandle = gFCircleQuery?.observe(.keyEntered, with: { (key, location) in 
      // if key fit some condition 
      ids += 1 
      if (ids >= 3) { 
       self.gFCircleQuery?.removeObserver(withFirebaseHandle: self.newRefHandle!) 
       completion() 
      } 
     }) 

     gFCircleQuery?.observeReady({ 
      completion() 
     }) 
} 

請在選配沒關係,這只是這個例子的代碼

從GoeFire文件(?):

要取消一個或所有的回調,地理查詢,請致電 removeObserverWithFirebaseHandle:或removeAllObserver :,分別爲 。

兩者都不起作用。

回答

1

引擎蓋下的Geofire觸發Firebase數據庫查詢。所有結果都是一次性從Firebase中檢索出來的,然後在本地觸發keyEntered事件(對於常規SDK),或者.childAdded用於常規SDK。

調用removeObserver(withFirebaseHandle:將停止Geofire檢索額外結果。但是對於任何已經檢索到的結果,它仍然會觸發keyEntered

的解決方案是增加一個附加條件而忽略那些已經檢索結果:

newRefHandle = gFCircleQuery?.observe(.keyEntered, with: { (key, location) in 
    if (id <= 3) { 
     // if key fit some condition 
     ids += 1 
     if (ids >= 3) { 
      self.gFCircleQuery?.removeObserver(withFirebaseHandle: self.newRefHandle!) 
      completion() 
     } 
     } 
    }) 
+0

謝謝!這是否意味着每次我想要獲得1-3個結果,我都會支付下載所有數千個對象的費用? –

+1

您將支付下載任何範圍內的物品。如果你想要包含一定數量的鍵的最小範圍,這種方法並不理想。鍵觸發的順序不是基於與查詢中心的距離,而是基於查詢範圍的其中一個角。如果你沒有得到足夠的結果,你最好從一個小範圍的查詢開始,然後發射另一個更寬範圍的地理查詢。 –

+0

我明白了。非常感謝你。 –