【发布时间】:2017-11-13 09:38:57
【问题描述】:
所以我之前在使用 firebase 的“观察”时遇到了问题,我意识到我无法从异步工作的代码块中获取变量值。一位用户告诉我使用完成处理程序来解决此问题,他的示例是:
func mapRegion(completion: (MKCoordinateRegion)->()) {
databaseHandle = databaseRef.child("RunList").child(runName).observe(.value, with: { (snapshot) in
let runData = snapshot.value as? [String: AnyObject]
self.minLat = runData?["startLat"] as? Double
self.minLng = runData?["startLong"] as? Double
self.maxLat = runData?["endLat"] as? Double
self.maxLng = runData?["endLong"] as? Double
print("testing")
print(self.minLat!)
print(self.maxLng!)
let region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: (self.minLat! + self.maxLat!)/2,
longitude: (self.minLng! + self.maxLng!)/2),
span: MKCoordinateSpan(latitudeDelta: (self.maxLat! - self.minLat!)*1.1,
longitudeDelta: (self.maxLng! - self.minLng!)*1.1))
completion(region)
})
}
并使用代码:
mapRegion() { region in
mapView.region = region
// do other things with the region
}
所以我尝试为另一个需要返回对象类型 RunDetail 的数组的方法重新创建它:
func loadRuns(completion: ([RunDetail]) -> ()) {
// we need name, distance, time and user
databaseHandle = databaseRef.child("RunList").observe(.value, with: { (snapshot) in
self.count = Int(snapshot.childrenCount)
print(self.count!)
// more stuff happening here to add data into an object called RunDetail from firebase
// add RunDetail objects into array called 'run'
})
completion(runs)
}
我不确定上面的设置是否正确^。
我仍然无法让完成处理程序正常工作(我真的不明白如何设置它)。有人可以帮助我并让我知道我是否正确设置了吗?谢谢。
【问题讨论】:
-
我修正了我的尝试,忘记在编辑原因中添加它。
标签: ios swift firebase swift3 firebase-realtime-database