我有这样的代码:
ref.child("skelbimai").observeSingleEvent(of: .value, with: {(snapshot) in
for child in (snapshot.children.allObjects as? [DataSnapshot])!{
let pinas = PinColorAnotation(color: UIColor.red)
pinas.coordinate = CLLocationCoordinate2D(latitude: child.childSnapshot(forPath: "lat").value as! Double, longitude: child.childSnapshot(forPath: "lon").value as! Double)
pinas.pinColor = Kategorija(child.childSnapshot(forPath: "cat").value as! Int).Color
pinas.title = String(Kategorija(child.childSnapshot(forPath: "cat").value as! Int).Name)
pinas.subtitle = String(child.childSnapshot(forPath: "price").value as! Double)
self.Map.addAnnotation(pinas)
}
})
问题是我无法将引脚保存到阵列。我有数组Pins = PinColorAnotation,当我调用Pins.append(pinas)并打印Pins.count时,我总是得到0。为什么呢?但是当我调用print inside loop时,它显示40。问题是,从Firebase下载后,我不得不稍后整理和管理图钉。但是我不能。如何解决这个问题?我是否需要执行以下所有管理逻辑:
ref.child("skelbimai").observeSingleEvent(of: .value, with: {(snapshot) in
for child in (snapshot.children.allObjects as? [DataSnapshot])!{
let pinas = PinColorAnotation(color: UIColor.red)
pinas.coordinate = CLLocationCoordinate2D(latitude: child.childSnapshot(forPath: "lat").value as! Double, longitude: child.childSnapshot(forPath: "lon").value as! Double)
pinas.pinColor = Kategorija(child.childSnapshot(forPath: "cat").value as! Int).Color
pinas.title = String(Kategorija(child.childSnapshot(forPath: "cat").value as! Int).Name)
pinas.subtitle = String(child.childSnapshot(forPath: "price").value as! Double)
self.Map.addAnnotation(pinas)
}
})
最佳答案
这样的事情应该起作用:
func getPins(completion: @escaping ([PinColorAnnotation]) -> Void){
var data: [PinColorAnnotation] = []
ref.child("skelbimai").observeSingleEvent(of: .value, with: {(snapshot) in
for child in (snapshot.children.allObjects as? [DataSnapshot])!{
let pinas = PinColorAnotation(color: UIColor.red)
pinas.coordinate = CLLocationCoordinate2D(latitude: child.childSnapshot(forPath: "lat").value as! Double, longitude: child.childSnapshot(forPath: "lon").value as! Double)
pinas.pinColor = Kategorija(child.childSnapshot(forPath: "cat").value as! Int).Color
pinas.title = String(Kategorija(child.childSnapshot(forPath: "cat").value as! Int).Name)
pinas.subtitle = String(child.childSnapshot(forPath: "price").value as! Double)
self.data.append(pinas)
}
completion(data)
})
}
然后,您可以在需要的地方调用该函数,例如
viewDidLoad
。然后可以将返回的数据设置为self.map
数组。如果有任何错误,我很抱歉,这是在平板电脑上完成的,因为我不在电脑旁。