我有以下代码,以便检索餐馆及其数据列表。但是,它不存储数据,每次我尝试返回数组时它返回nil。但如果我打印它,打印数据。有什么建议吗?
func getRestaurants()-> Array<Restaurant>{
var baruri = [Restaurant]()
dataBaseRef.child("AthensRestaurants/Restaurants").observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
print(snap)
if let restaurantData = snap.value as? Dictionary<String, AnyObject> {
let restaurant = Restaurant(restaurantData: restaurantData)
baruri.append(restaurant)
print(baruri)
}
}
}
})
return baruri
}
答案 0 :(得分:1)
firebase observe
是一个异步回调函数,因此它将在完成后运行。换句话说,您的return baruri
将始终在值返回之前运行。您可以使用完成处理程序来获取所需的值。
var restaurants = [Restaurant]()
func getRestaurants(completion: @escaping (Array<Restaurant>) -> Void){
var baruri = [Restaurant]()
dataBaseRef.child("AthensRestaurants/Restaurants").observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
print(snap)
if let restaurantData = snap.value as? Dictionary<String, AnyObject> {
let restaurant = Restaurant(restaurantData: restaurantData)
baruri.append(restaurant)
print(baruri)
completion(baruri)
}
}
}
})
}
// Call this function with call back
getRestaurants { restaurants in
self.restaurants = restaurants
}