本文介绍了GeoFire + Swift 3不能停止观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用GeoFire并尝试仅获取3个满足某些条件的结果.这是我的情况,并不会阻止观察者.有数千个结果,我得到了所有结果,但我只需要3个.我基于此答案,但它在如您所见,我的情况.请有人帮忙吗?

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

请不要介意Optionals(?),它仅用于此示例代码

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

来自GoeFire文档:

From GoeFire documentation:

两个都不起作用.

推荐答案

引擎盖下的Geofire会触发Firebase数据库查询.一次性从Firebase检索所有结果,然后在本地为每个结果触发keyEntered事件(对于常规SDK,为.childAdded).

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).

致电removeObserver(withFirebaseHandle:将阻止Geofire检索其他结果.但对于已检索到的任何结果,它仍将触发keyEntered.

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

这篇关于GeoFire + Swift 3不能停止观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:17