【发布时间】:2019-05-18 03:13:26
【问题描述】:
1- 我的应用中的所有用户每 2.5 分钟使用 Timer 将他们的位置发送到 GeoFire。
2- 其他用户也会查询 GeoFire 以查找距离他们 1 英里半径内的任何用户(例如 10 个用户)。我得到这 10 个用户,然后将它们添加到一个数组中。
3- 然后,我使用这 10 个用户的 userId(geoRef 键)循环遍历数组。我去他们的数据库参考并搜索以查看它们是否符合某些标准。如果他们这样做,我将它们添加到不同的数组中(例如,现在这个子集数组中有 5 个用户)
4- 由于每 2.5 分钟将每个用户的位置发送到 GeoFire,这意味着该子集中的这 5 个用户的位置可能与他们首次添加到子集数组时的位置不同。
我可以使用计时器来查询这 5 个用户的位置。问题是我如何查询 GeoFire 以仅从这 5 个用户中获取每个用户的位置?我不想再次查询该 1 英里区域内的每个人,否则它会让我得到相同的结果10 个用户
// I have a Timer firing this off
func queryLocationOfSubsetOfUsersInRadius() {
let geofireRef = Database.database().reference().child("geoLocations")
let geoFire = GeoFire(firebaseRef: geoFireRef)
let dispatchGroup = DispatchGroup()
for user in subsetOfUsersInRadius {
dispatchGroup.enter()
let userId = user.userId
// I don't know if this is the right method to use. I only added it here because I saw it has observeValue on it
geoFire.observeValue(forKeyPath: userId, of: Any?, change: NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
// *** HOW TO GET THE USERS NEW LOCATION and use dispatchGroup.leave() as each one is obtained??? ***
dispatchGroup.leave()
}
dispatchGroup.notify(queue: .global(qos: .background)) {
// now animate the annotation from the user's inital old location (if they moved) on the mapView to their new location on the mapView. It's supposed to look like Uber's cars moving. Happens on main thread
}
}
下面的支持代码
var queryHandle: UInt?
var regionQuery: GFRegionQuery?
var usersInRadius = [User]() // has 10 users
var subsetOfUsersInRadius = [User]() // of the 10 only 5 fit some criteria
let geofireRef = Database.database().reference().child("geoLocations")
let geoFire = GeoFire(firebaseRef: geofireRef)
// region: MKCoordinateRegion was previously set at 1 mile 1609.344 meters
regionQuery = geoFire.query(with: region)
queryHandle = regionQuery?.observe(.keyEntered, with: { [weak self](key: String!, location: CLLocation!) in
let user = User()
user.userId = key
user.location = location
self?.usersInRadius.append(user)
})
regionQuery?.observeReady({ [weak self] in
self?.sortUsersInRadius(arr: self!.usersInRadius)
})
func sortUsersInRadius(arr: [User]) {
if let queryHandle = queryHandle {
regionQuery?.removeObserver(withFirebaseHandle: queryHandle)
}
let dispatchGroup = DispatchGroup()
for user in arr {
let userId = user.userId
someDatabaseRef.child(userId).observeSingleEvent(of: .value, with: { (snapshot) in
// if snapshot contains some critera add that user to the subSet array
self?.subsetOfUsersInRadius.append(user) // only 5 users fit this criteria
dispatchGroup.leave()
})
}
dispatchGroup.notify(queue: .global(qos: .background)) {
// add an annotation to mapView to show the initial location of each user from subsetOfUsersInRadius. Happens on main thread
}
}
【问题讨论】:
标签: ios swift firebase geolocation