1

Hi I'm trying to get the numOfVids in Firebase db so I can return that number in my numberOfItemsInSection. But it returns 0 instead of 6. I know it returns 0 because it's reading the empty variable instead of the one in the observeSingleEvent.

Is there any way for me to get the modified numOfVids instead of the empty numOfVids?

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    var numOfVids = Int() // 0
    let videosRef = FIRDatabase.database().reference().child("users/\(currentUserID)/videos")

    videosRef.observeSingleEvent(of: .value, with: { (snapshot) in
        //get user value
        numOfVids = Int(snapshot.childrenCount)
        print(numOfVids) //prints 6

    })

    return numOfVids //returns 0
}

Thank you in advance!

Erik Batista
  • 227
  • 2
  • 15
  • 9
    **Never ever** put an asynchronous task in a method which is supposed to return something. It won't work. Find another solution. For example use a data source model, load the data in `viewWillAppear` and reload the collection view in the completion handler of the observing method. – vadian Aug 05 '17 at 14:04
  • Exactly, doing this work in the methods of UICollectionViewDataSource is bad approach. – Kiryl Bielašeŭski Aug 05 '17 at 15:19

2 Answers2

0

Try :-

var numOfVids : Int = 0   
@IBOutlet weak var my_CollectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.my_CollectionView.delegate = self
    self.my_CollectionView.dataSource = self

    loadData { (check) in
        print(check)
    }

}


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

     // Use only when you want to reload your data every time your view is presented.
         /*
     loadData { (check) in
        print(check)
    }
    */
}

func loadData(completionBlock : @escaping ((_ success : Bool?) -> Void)){

    Database.database().reference().child("your_PATH").observeSingleEvent(of: .value, with: {(Snap ) in

        // Once you have retrieved your data
        // Update the count on the class local variable --  numOfVids
        // Reload your collectionView as ..

        self.my_CollectionView.reloadData()
        completionBlock(true)

  })

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return numOfVids

  }
Dravidian
  • 9,945
  • 3
  • 34
  • 74
-4

Try this:

let videosRef = FIRDatabase.database().reference().child("users/\(currentUserID)/videos")

    videosRef.observeSingleEvent(of: DataEventType.value, with: { (snapshot) in
        for data in snapshot.children.allObjects as! [DataSnapshot] {
            if let data = data.value  {

              self.numOfVids = self.numOfVids + 1

            }
        }
        print(numOfVids)
    })

And regarding the variable numOfVids:

var numOfVids = 0

That should work thanks

0xMe
  • 49
  • 6