即时尝试与firebase一起工作,我做了这个功能,将一个数组“节能”保存到另一个视图控制器,并将它们显示在一个tableView上。Swift Make For Loop等待异步函数结束
我发现一个问题,即在数据来自服务器之前,for循环结束,并且firebase的回调即将到来,您可以在其中看到“fir(self.goodOffer ...)”行结束的firebase回调。
也许有人知道我该如何让for循环等待firebase回调结束?
thx。
geocodeAddress(totalFromLocation, callback: { (location) in
if location != nil {
fromLocation = location
self.geocodeAddress(totalToLocation, callback: { (location) in
if location != nil {
toLocation = location
mainDistance = Int(self.distanceCalculate(fromLocation!, locationTwo: toLocation!))
print(mainDistance)
REF_BUSSINES_OFFERS.queryOrderedByKey().queryEqualToValue("north").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
print("in snap")
if let value = snapshot.value {
if self.isAlavator {
if let area = value["north"] {
if let data = area!["withAlavator"]! {
if let bids = data["bids"] as? Int {
for i in 1..<bids+1 {
if let bid = data["\(i)"] {
let bidFromSize = bid!["fromSize"] as! Int
let bidToSize = bid!["toSize"] as! Int
let bidFromDistance = bid!["fromDistance"] as! Int
let bidToDistance = bid!["toDistance"] as! Int
if mainDistance >= bidFromDistance && mainDistance <= bidToDistance {
if Int(totalSize) >= bidFromSize && Int(totalSize) <= bidToSize {
let price = String(bid!["price"])
let name = bid!["name"] as! String
let phoneNumber = bid!["phoneNumber"] as! String
var logoImageData: NSData!
LOGOS_REF.child("\(phoneNumber)").dataWithMaxSize(3 * 1024 * 1024, completion: { (data, error) in
if error != nil {
logoImageData = UIImagePNGRepresentation(UIImage(named: "company")!)
} else {
logoImageData = data
}
let offer = Offer(logoImage: logoImageData, name: name, price: price)
self.goodOffers.append(offer)
print("fir \(self.goodOffers[0].price)")
})
}
}
}
print(i)
}//end of for
print("out")
//self.changgeViewToTable()
}
好悲伤,你的代码跑离屏幕的一侧。不能切换'返回'或什么东西,所以你可以早点回来,而不是嵌套你知道深层次多少层次的东西。 (还有什么是“alavator”?) –
当您修复错误时,您应该将此发布到[Code Review](http://codereview.stackexchange.com/),您的代码是恶梦素材 – Kametrixom