Reputation: 25
After parsing JSON I got my data in arraOfData of ViewController, but collectionView not display this. If I use static array all working. collectionview.reloadData() is not working. In my opinion, need somehow waiting data from parsing, then try load collectionView. I tried use refresherControler for waiting data, but I don't know where put method "endRefreshing" (i guess startRefreshing need in ViewDidLoad) If I use reloadData like didSet in arraOfData I got error cause collectionView is nil. Use reloadData right after got data from parsing same didn't work for me And a big request to tell a couple of resources (articles) on this topic, I feel that I have big problems with displaying data and in what sequence functions start to load. Thanks a lot.
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var arraOfData = [GettingMoney]() {
didSet {
print("Changes: \(arraOfData.count)")
}
}
// let arr = ["1", "2", "3"] - test, if i use this array, collectionView display data
override func viewDidLoad() {
super.viewDidLoad()
GettingMoney.fetchData()
collectionView.dataSource = self
collectionView.delegate = self
}
}
extension ViewController: UICollectionViewDelegate,
UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arraOfData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCellId", for: indexPath) as? CollectionViewCell
cell?.currentCurrency.text = "\(arraOfData[indexPath.row])"
return cell!
}
}
Upvotes: 0
Views: 168
Reputation: 100503
As this
GettingMoney.fetchData()
is a sign of asynchronous process that doesn't reload the collection , so do
func fetchData(completion:@escaping ([String]) -> ()) {
Api.load {
completion(arr)
}
}
Then use like
GettingMoney.fetchData { arr in
self.arraOfData = arr
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
A not direct case like yours is here Returning data from async call in Swift function
Upvotes: 2