I have this closure which I use to populate my array and dictionary. However, when I try to use it outside the function, it's empty. I understand that this closure works on an asynchronous thread, so is it right to assume that I try to access that variable before it's been populated? As a result, I get an empty array. Here is my code.
class HomeCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UIGestureRecognizerDelegate {
var entries = [String: DiaryEntry]()
var entryIDS = [String]()
var searchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.register(DiaryCell.self, forCellWithReuseIdentifier: "homeCell")
collectionView?.backgroundColor = UIColor.white
navigationController?.hidesBarsOnSwipe = true
if let userID = FIRAuth.auth()?.currentUser?.uid {
FirebaseService.service.getUserEntriesRef(uid: userID).observe(.value, with: { [weak weakSelf = self] (snapshot) in
let enumerator = snapshot.children
while let entry = enumerator.nextObject() as? FIRDataSnapshot {
weakSelf?.entryIDS.append(entry.key)
weakSelf?.entries[entry.key] = DiaryEntry(snapshot: entry)
}
weakSelf?.entryIDS.reverse()
weakSelf?.collectionView?.reloadData()
})
print("Entries: \(entryIDS.count) ")
}
// Do any additional setup after loading the view.
}
What's the best way to deal with such a multithreaded execution?