【问题标题】:Can't get number of children from a snapshot无法从快照中获取孩子的数量
【发布时间】:2016-11-15 05:30:43
【问题描述】:

我无法获取快照返回的子项数量。当我在另一个位置写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
            }

}

【问题讨论】:

  • 它现在可以工作了,我做了一个静态类并在 AppDelegate 中对其进行了收费
  • self.firebase = FIRDatabase.database().reference(fromURL:"firebaseURL").child("featuredCars") firebase?.observeSingleEvent(of: .value, with: { GetFeaturedCars 中的快照。 newCars = 快照

标签: firebase firebase-realtime-database swift3


【解决方案1】:

该代码对我有用。

我猜你正在将 print(self.newCars) 移到 Firebase 块之外(关闭)。

Firebase 返回数据需要时间,并且该数据仅在闭包内有效。

如果 print 语句在闭包之外,它会在数据从 Firebase 返回之前运行,并且将为 null。

【讨论】:

    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 2023-04-10
    • 2016-12-28
    • 1970-01-01
    • 2017-03-01
    相关资源
    最近更新 更多