Reputation: 25
Im super newly in swift (learning a couple of weeks) and sorry for my english. i don't know how to avoid checking method "cellForItemAt indexPath". I tryed to play with refreshingControl but its not working. I got error at the line "let arry = arrayOfData[indexPath.row] // <-- here is got error: Fatal error: Index out of range". If i comment this line all work fine (and refreshControll). My arrayOfData is empty when collectionView trying load, if continue (when i debaging) eventually i will get my data from arrayOfData (its data from JSON). But compiler wont check that method again (if i try check isRefresh true of false).
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
private var isRefreshing = true
var arrayOfData = [GettingMoney]()
override func viewDidLoad() {
super.viewDidLoad()
let refreshControl = UIRefreshControl()
refreshControl.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
collectionView.refreshControl = refreshControl
collectionView.refreshControl?.beginRefreshing()
fetchData()
collectionView.dataSource = self
collectionView.delegate = self
}
func fetchData () {
let url = "SOMEAPI"
guard let urlString = URL(string: url) else { return }
URLSession.shared.dataTask(with: urlString) { (data, _, _) in
guard let data = data else { return }
do {
let getData = try JSONDecoder().decode(GettingMoney.self, from: data)
print("getSomeData")
DispatchQueue.main.async {
self.arrayOfData = [getData]
self.collectionView?.reloadData()
self.collectionView.refreshControl?.endRefreshing()
print("reload Data")
}
} catch {
print("Its a error")
}
}.resume()
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCellId", for: indexPath) as? CollectionViewCell {
let arry = arrayOfData[indexPath.row] // <-- here is got error: Fatal error: Index out of range
print("is Ok")
cell.currectCurrency.text = "\(arry.USD))"
print(arrayOfData)
return cell
}
return UICollectionViewCell()
}
}
Upvotes: 1
Views: 58
Reputation: 15248
Update numberOfItemsInSections
as below,
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.arrayOfData.count
}
Upvotes: 1