Reputation: 5101
I don't know what am I doing wrong.
I have a viewController with a collectionView.
I have set the collectionView delegates as follows, in viewController and also at storyboard:
modelosCV.delegate = self
modelosCV.dataSource = self
I have created all collectionView methods:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filtrados ? modelosFiltrados.count : modelos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellModelos = collectionView.dequeueReusableCell(withReuseIdentifier: "modelo", for: indexPath) as! ModelosCollectionViewCell
print(filtrados ? modelosFiltrados[indexPath.row].icono : modelos[indexPath.row].icono)
let foto_modelo = filtrados ? modelosFiltrados[indexPath.row].icono : modelos[indexPath.row].icono
let modelo_nombre = filtrados ? modelosFiltrados[indexPath.row].nombre : modelos[indexPath.row].nombre
cellModelos.modelo_nombre.text = modelo_nombre
let url = URL(string: "https://j../iconos/"+foto_modelo)
UIImage.loadFrom(url: url!) { image in
cellModelos.modelo_icono.image = image
}
return cellModelos
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let padding: CGFloat = 50
let collectionViewSize = collectionView.frame.size.width - padding
return CGSize(width: collectionViewSize/2, height: 242)
}
I am populating the collectionView from a remote JSON source:
func downloadJSONModelos(completed: @escaping () -> ()) {
var categoria = ""
let cat = self.defaults.string(forKey: "nueva_alarma_categoria")
if (cat == "Móviles"){
categoria = "3"
}
if (cat == "Tablets"){
categoria = "5"
}
if (cat == "Smartwatches"){
categoria = "7"
}
let marca_id = self.defaults.string(forKey: "nueva_alarma_marca_id")
let url = URL(string: "https:.....php?marca="+marca_id!+"&cat="+categoria)
URLSession.shared.dataTask(with: url!) { (data,response,error) in
print(data as Any)
print(response as Any)
if error == nil {
do {
self.modelos = try JSONDecoder().decode([Modelos].self, from: data!)
DispatchQueue.main.async {
completed()
}
}catch{
}
print(self.modelos)
}
}.resume()
}
The app is receiving the JSON array as it is printed in the output, but the collectionView remains empty.
What am I missing?
Upvotes: 2
Views: 86
Reputation: 1158
Add this to your viewDidLoad
:
yourCollectionView.register(UINib(nibName: "yourXibName", bundle: nil), forCellWithReuseIdentifier: "modelo")
And reload your collectionView
with yourCollectionView.reloadData()
at where you append element to your array from JSON
.
Hope it helps...
Upvotes: 2