Nick
Nick

Reputation: 492

Retrieve data from Firebase before loading view iOS

I'm working on an app in which a user has a specific amount of posts. To keep track of the amount of posts that a user has, in FirebaseDatabase there is a value which stores this number.

I need to retrieve this value before loading my collection view.

Here is how I am retrieving this value from Firebase:

var count = 0

private func retrievePostCount() {

       let userID = Auth.auth().currentUser?.uid

       ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        let count = value?["postCount"] as? Int ?? 0
        self.count = count

    }) { (error) in
        print(error.localizedDescription)
    }
}

I call this method before loading the view.

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

After I retrieve the data, I then call count when assigning the cell number.

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.count
}

Here is what the structure of the database looks like.

enter image description here

I think the issue may be that the view is loading too fast before the data is retrieved. How can I fix this?

Upvotes: 0

Views: 839

Answers (1)

Kamran
Kamran

Reputation: 15248

Once you set the count retrieved from the api, you need to reload the collectionView as below so that your new count is returned from the numberOfItemsInSection method,

ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        let count = value?["postCount"] as? Int ?? 0
        self.count = count

        // Reloading collectionView to reflect the new count
        self.collectionView.reloadData()

    }) { (error) in
        print(error.localizedDescription)
}

Upvotes: 1

Related Questions