2016-11-14 15 views
-1

スナップショットから返される子の数を取得できません。スナップショットから子の数を取得できません

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 
      } 

} 
+0

それは今仕事、私は静的クラスを作って、私はAppDelegate –

+0

self.firebase = FIRDatabase.database()を参照して、それを充電。。(fromURL: "firebaseURL")子( "featuredCars") firebase?。 observeSingleEvent(の:.value、with:{snapshot in } GetFeaturedCars.newCars = snapshot –

答えて

0

コードは私のために働いていること:私は別の位置にprint(self.newCars)を書くとき、私はいつもSnap ((null)) (null)を取得します。

Firebaseブロック(クロージャ)の外でプリント(self.newCars)を動かしていると思います。

Firebaseがデータを返すのに時間がかかり、そのデータはクロージャ内でのみ有効になります。

print文がクロージャの外側にある場合、Firebaseからデータが返される前にprint文が実行されていて、nullになります。

関連する問題