Firebase 网站上给出了从 Firestore 检索给定点 50 公里位置内所有位置的代码。这里是:
// Find cities within 50km of London
let center = CLLocationCoordinate2D(latitude: 51.5074, longitude: 0.1278)
let radiusInM: Double = 50 * 1000
// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
let queryBounds = GFUtils.queryBounds(forLocation: center,
withRadius: radiusInM)
let queries = queryBounds.map { bound -> Query in
return db.collection("cities")
.order(by: "geohash")
.start(at: [bound.startValue])
.end(at: [bound.endValue])
}
var matchingDocs = [QueryDocumentSnapshot]()
// Collect all the query results together into a single list
func getDocumentsCompletion(snapshot: QuerySnapshot?, error: Error?) -> () {
guard let documents = snapshot?.documents else {
print("Unable to fetch snapshot data. \(String(describing: error))")
return
}
for document in documents {
let lat = document.data()["lat"] as? Double ?? 0
let lng = document.data()["lng"] as? Double ?? 0
let coordinates = CLLocation(latitude: lat, longitude: lng)
let centerPoint = CLLocation(latitude: center.latitude, longitude: center.longitude)
// We have to filter out a few false positives due to GeoHash accuracy, but
// most will match
let distance = GFUtils.distance(from: centerPoint, to: coordinates)
if distance <= radiusInM {
matchingDocs.append(document)
}
}
}
// After all callbacks have executed, matchingDocs contains the result. Note that this
// sample does not demonstrate how to wait on all callbacks to complete.
for query in queries {
query.getDocuments(completion: getDocumentsCompletion)
}
我遇到的问题是matchingDocs
(数据库中的位置应该附加到的空数组)每次都返回空。
我已仔细检查数据库中的中心位置和示例位置彼此相距不超过 50 公里。该代码能够检索数据库中的四个文档,我知道这一点,因为如果我在最后一个 for 循环中放置打印语句,我会打印 4 次内容。
我需要一个解释到底是什么getDocumentsCompletion
函数之所以这样做,是因为我不完全理解它的作用,或者调用是如何工作的。调用函数的地方没有传递任何参数。
我还在以下内容中添加了打印语句getDocumentsCompletion
函数,但没有任何内容被打印出来,所以我相信我的问题就在那里。我想要一个关于到底发生了什么的解释,以便我可以更好地解决这个问题。