【问题标题】:GeoFire + Swift 3 can't stop observingGeoFire + Swift 3 无法停止观察
【发布时间】:2017-12-24 01:22:37
【问题描述】:

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

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(?) 这只是为了这个示例代码

来自 GoeFire 文档:

要取消地理查询的一个或所有回调,请调用 removeObserverWithFirebaseHandle: 或 removeAllObservers:, 分别。

两者都不工作。

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database geofire


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!这是否意味着我每次想要获得 1-3 个结果时都要为下载所有数千个对象付费?
    • 您需要为下载范围内的任何项目付费。如果您想要包含一定数量的键的最小范围,这种方法并不理想。键触发的顺序不是基于与查询中心的接近程度,而是基于查询范围的一个角。您最好从一个范围较小的查询开始,然后如果您没有获得足够的结果,则触发另一个范围更广的地理查询。
    • 我明白了。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2017-07-05
    • 2018-07-04
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2019-05-23
    相关资源
    最近更新 更多