【发布时间】:2021-11-21 17:57:53
【问题描述】:
我正在尝试 Firebase GeoFire,但关闭总是让我很头疼。 Firebase 在他们的文档中提供了这个示例代码 sn-p
// 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)
}
不幸的是,它并没有证明我需要什么......
我希望它在预设的时间间隔内触发,所以我有一个这样的计划:
locationTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(getLocations), userInfo: nil, repeats: true)
那么我的代码和示例差不多:
var matchingDocs = [QueryDocumentSnapshot]()
@objc func getLocations() {
let center = CLLocationCoordinate2D(latitude: lat, longitude: lon)
let radiusInM: Double = 10000
// 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("geopoints")
.order(by: "geohash")
}
// 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)
}
}
}
等待回调完成并在 getLocations() 函数之外使用包含所有地理点的 matchDocs 继续执行程序的正确方法是什么?感谢您的任何建议。
【问题讨论】:
-
不要使用
Timer。运行搜索异步进程。 -
使用
Timer有什么问题? -
您的应用所要做的就是等待数据传输并在可用时显示它。使用
Timer不是正确的方法。 -
好的,没关系。我仍然需要一些建议来处理关闭。有什么指点吗?
-
向搜索引擎询问您对“Swift firestore 完成处理程序”或其他内容的偏好。
标签: swift firebase google-cloud-firestore geofire