CollectionView not reload data

CollectionView not reload data

I have a TableView where each item has a code, when the user chooses any item of this Table it has to fetch data on a server via HTTP-POST and load a CollectionView inside another View.

I have a TableView where each item has a code, when the user chooses any item of this Table it has to fetch data on a server via HTTP-POST and load a CollectionView inside another View.

When this new view opens the data collection is empty then squeeze a Thread to fetch the data via HTTP-POST, the search is working but the data does not appear in the CollectionView after the collection is populated.

This is my code:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

@IBOutlet var root: UIView! @IBOutlet weak var lbDescricao: UILabel! @IBOutlet weak var colData: UICollectionView!

var desc: String = "" var codigoCategoria: Int! var listaProdutos: Array<Produto>! var items: [IndexPath] = Array()

override func viewDidLoad() { super.viewDidLoad() self.doPostProdutos() lbDescricao.text = self.desc print( self.listaProdutos ) // Here it show “nil” }

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return listaProdutos.count }

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.items.append(indexPath) }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionCellProduto

cell.imgProduto.image = UIImage( named: listaProdutos[indexPath.item].imagem )
cell.lbNome.text = listaProdutos[indexPath.item].nome
cell.lbPreco.text = "R$ " + String( listaProdutos[indexPath.item].preco )

return cell;

}

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: collectionViewSize/2 )

}

func doPostProdutos() { let parameter = ["categoria":self.codigoCategoria]

let url = URL(string: "localhost/adm/api/produtos/produtosCategoria.php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let httpBody = try? JSONSerialization.data(withJSONObject: parameter, options: [])
request.httpBody = httpBody


let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
    if let response = response {
        print( response )
    }

    if let data = data {
        DispatchQueue.main.async{ // Thread
            do {
                self.listaProdutos = Array()

                let json = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]

                for prod in json {
                    let nome = prod["nome"] as! String
                    let preco = (prod["preco"] as! NSString).doubleValue
                    let img = prod["imagem"] as! String

                    let produto: Produto = Produto(nome: nome, preco: preco, img: img)

                    self.listaProdutos.append(produto)
                }

                // Refresh
                print( self.listaProdutos )
                self.colData.reloadData()
                self.colData.reloadItems(at: self.items)
            }
            catch {
                print(error)
            }
        }
    }
}.resume()

} }

What am I doing wrong?

ios json swift

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Hire Dedicated Swift Developers

Want to create a native iOS application for your Startup? **[Hire Dedicated Swift Developers](https://hourlydeveloper.io/hire-dedicated-swift-developer/ "Hire Dedicated Swift Developers")** for end-to-end services like development, migration...

What is JSON - JSON Parsing in Swift

What is JSON and how do you parse JSON in Swift? JSON stands for JavaScript Object Notation and it's a way to represent data in a standard way. Learn how to parse JSON in Swift using the Codable protocol. We take the response JSON data from a real API call and then parse it in Swift!

How to change the UITextfield text with data from JSON based on the value from UISlider in Swift 4?

Right now I have the UIText field hard coded and changing according to the value on the UISlider.

iOS App Development: How Apple's iOS 13 & Swift 5 Will Change App Development Industry

Want to know how Apple's iOS 13 & Swift 5 will change the iOS app development industry? Refer to this blog that contains in-detail information on it.

Easy way to save the class object in user defaults - Swift iOS

Easy way to save the class object in user defaults - Swift iOS Text tutorial: http://adnan-tech.com/easy-way-to-save-the-class-object-in-user-defaults-swift-...