Firebase Can';无法从快照中获取子级数
我无法获取快照返回的子对象数。当我在另一个位置写入Firebase Can';无法从快照中获取子级数,firebase,firebase-realtime-database,swift3,Firebase,Firebase Realtime Database,Swift3,我无法获取快照返回的子对象数。当我在另一个位置写入print(self.newCars)时,我总是得到Snap((null))(null): class NewCarsViewController: UICollectionViewController { var firebase: FIRDatabaseReference? var newCars = FIRDataSnapshot() override func viewDidLoad() { s
print(self.newCars)
时,我总是得到Snap((null))(null)
:
class NewCarsViewController: UICollectionViewController {
var firebase: FIRDatabaseReference?
var newCars = FIRDataSnapshot()
override func viewDidLoad() {
super.viewDidLoad()
self.firebase = FIRDatabase.database().reference(fromURL:"https://firebaseURL/").child("featuredCars")
firebase?.observeSingleEvent(of: .value, with: { snapshot in
self.newCars = snapshot
print("halim")
print(self.newCars)
// print(snapshot.childrenCount) // I got the expected number of items
for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {
// print(rest.value ?? "")
}
})
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewCarCell", for: indexPath) as UICollectionViewCell
return cell
}
}
那个密码对我有用 我猜你是在把印刷品(self.newCars)移到Firebase区块外(关闭) Firebase返回数据需要时间,并且该数据仅在闭包内有效
如果print语句在闭包之外,则它在从Firebase返回数据之前运行,它将为null。它现在可以工作,我创建了一个静态类,并在AppDelegateself.Firebase=FIRDatabase.database().reference(fromURL:“firebaseURL”).child(“featuredCars”)Firebase?中对其进行了计费。observeSingleEvent(属于:。值,其中:{snapshot in GetFeaturedCars.newCars=snapshot