使用 geofire 进行一次性位置更新? swift 4

use geofire for a one time location update? swift 4

所以 Geofire 文档是这样说的:

There are three kinds of events that can occur with a geo query:

Key Entered: The location of a key now matches the query criteria.

Key Exited: The location of a key no longer matches the query criteria.

Key Moved: The location of a key changed but the location still matches the query criteria.

但是由于这些都是实时的,我如何才能让它只查询 一次,比如说,在按下按钮时,并存储密钥?我的 locationManager.didUpdateLocations 看起来像这样:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        if String(describing: Date()) == String(describing: location.timestamp) {

            var query = geoFire.queryAtLocation(location, withRadius: 10)
            query.observe(.keyEntered, with: { (key, location) in
                // Is this where I store the keys?
                print("Key '\(key)' entered the search area and is at location '\(location)'")
            })

            manager.stopUpdatingLocation()
        }
    }
}

我试过了,但是返回的结果不是决定性的。即使我的位置没有移动(在模拟器上),它有时也会遗漏一些键或重复计算其他键。

You can use ObserveReadyWithBlock: 知道初始数据何时加载完毕,然后取消查询。

Adds an observer that is called once all initial GeoFire data has been loaded and the relevant events have been fired for this query.

这是 javascript 中的示例,来自 github 上的 similar discussion,但对于 iOS 也是一样的。

var items = []; // save the items

var onKeyEnteredRegistration = geoQuery.on("key_entered", function(key, location, distance) {
  console.log(key + " entered query at " + location + " (" + distance + " km from center)");
  items.push(key);
});

geoQuery.on("ready", function() {
  // This will fire once the initial data is loaded, so now we can cancel the "key_entered" event listener
  onKeyEnteredRegistration.cancel();
});

但是检索项目不是很低效吗one-by-one?

不是真的。 Firebase 经过高度优化,并通过 websockets 保持持久连接打开。