0

When you start the application, you should get a line from the Firestore documents and write to an array, (array)

    var items = [String]()
override func viewDidLoad() {
        let db = Firestore.firestore()
        db.collection("cities").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    print("\(document.documentID) => \(document.data())")
                    self.items.append(document.data()["title"] as! String)
                }
            }
        }

    }

then in the cell creation function, the text should be changed to a line from the array.

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! colCell
        print(self.items)
        cell.myLabel.text = self.items[indexPath.item]

        return cell
    }

But the array with strings from the firestore is not updated in the cell creation function. Why?

(I printed out array in viewDidLoad and in cell, it's updated in viewDidLoad and not updated in cell)

1
  • did you call collectionView.reloadData? Commented Mar 24, 2019 at 23:48

2 Answers 2

2

You need to reload the collectionView as the call to firestore is asynchronous

for document in querySnapshot!.documents {
   print("\(document.documentID) => \(document.data())")
   self.items.append(document.data()["title"] as! String)
}
self.collectionView.reloadData()
Sign up to request clarification or add additional context in comments.

Comments

0

You can reload the given cell after updating the date like this,

collectionView.reloadItemsAtIndexPaths(arrayOfIndexPaths)

it is optimised way to update UICollectionView.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.