iosswiftuicollectionviewviewdidload

numberOfItemsInSection func calling before viewdidload()


Here I am first retrieving an image from firebase then adding it to an locationImage array,which will be later added to collectionView.

import UIKit
import Firebase
import FirebaseStorage

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

var locationImage = [UIImage(named: "hawai"), UIImage(named: "mountain")]

override func viewDidLoad() {
    super.viewDidLoad()

    retrieveData()
}


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

    print(locationImage.count)
    return locationImage.count
}
func retrieveData(){
    let database = FIRDatabase.database().reference()
    let storage = FIRStorage.storage().reference()

    let imageRef = storage.child("blue blurr.png")

    imageRef.data(withMaxSize: (1*1000*1000)) { (data, error) in
        if error == nil{

            let tempImage = UIImage(data: data!)
            self.locationImage.append(tempImage)
            print("HELLLLLOOOO WOOOOORRRLLLDDDD")
            print(self.locationImage.count)
        }
        else{
            print(error?.localizedDescription)
        }
    }
    return
}

}

Here the retrieveData() function is calling before collectionView().Instead viewdidload should be called first,how can I do that,can someone help ?


Solution

  • You don't want the collectionView to be called before ViewDidLoad?

    override func viewDidLoad() {
        super.viewDidLoad()
    
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    

    But this shouldn't worry you, because if the array you are using to initialise the CollectionView is empty, it wouldn't matter if the call goes to the numberOfItemsInSection method.

    What you require here is to call a reload after you have data in your locationImage. So right after your self.locationImage.append(tempImage), add:

    self.collectionView.reloadData()