Reputation: 2457
I have a controller with a collectionView that pulls item data from an API. The data is stored in a struct->static variable. I need to access this data from multiple areas in the app.
How can I reload the tableView data when the API data comes in?
Controller
class CollectionsViewController: UIViewController {
}
extension CollectionsViewController: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Brand.products.count
}
}
API data
struct Brand{
static var products:[Product] = []
static func fetchProducts(){
let url = URL(string: "www.someAPIexample.com")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do{
// update data (cut this part for readability)
self.products = data
// reload the controller.collectionView that uses this
(how do I get this controller from here).collectionView.reloadData()
}catch{
print(error)
}
}).resume()
}
}
Upvotes: 2
Views: 97
Reputation: 285064
The usual way is to add a completion handler
static func fetchProducts(completion: () -> Void) {
...
self.products = data
completion()
...
}
And call it
Brand.fetchProducts() {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
Upvotes: 2