GeoFire + Swift 3 can't stop observing

强颜欢笑 提交于 2020-07-09 06:40:45

问题


I'm using GeoFire and trying to fetch only 3 results that satisfy some conditions. This it my case and it doesn't stop observer. There are several thousands results and I get it all but I need only 3. I based on this answer but it does't work in my case as you can see. Please can somebody help?

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()
        })
}

Please, never mind on Optionals(?) it is just for this example code

From GoeFire documentation:

To cancel one or all callbacks for a geo query, call removeObserverWithFirebaseHandle: or removeAllObservers:, respectively.

Both are not working.


回答1:


Geofire under the hoods fires a Firebase Database query. All results are retrieved from Firebase in one go and then locally it fires the keyEntered event for each of them (or .childAdded for the regular SDK).

Calling removeObserver(withFirebaseHandle: will stop Geofire from retrieving additional results. But it will still fire keyEntered for any results that have already been retrieved.

The solution is to add an additional condition to ignore those already retrieved results:

   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()
        }
      }
    })


来源:https://stackoverflow.com/questions/45179245/geofire-swift-3-cant-stop-observing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!