UICollectionView不重新加载数据

时间:2019-01-30 13:49:40

标签: ios json swift uicollectionview http-post

我有一个TableView,其中每个项目都有一个代码,当用户选择该表的任何项目时,它必须通过HTTP-POST获取服务器上的数据,并将CollectionView加载到另一个View中。

当此新视图打开时,数据集合为空,然后挤压线程以通过HTTP-POST提取数据,搜索正在工作,但填充集合后数据未出现在CollectionView中。

这是我的代码:

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()
}
}

我在做什么错了?

2 个答案:

答案 0 :(得分:1)

您需要将UICollectionView上的委托和数据源设置为self

colData.delegate = self
colData.dataSource = self

您可以在viewDidLoad()

上执行此操作

答案 1 :(得分:0)

您需要在此处添加这2行

override func viewDidLoad() {
   super.viewDidLoad()
   self.doPostProdutos()
   lbDescricao.text = self.desc

   colData.delegate = self //this 2 line
   colData.dataSource = self

   print( self.listaProdutos ) // Here it show “nil”
}

添加以上两行,以便您的collectionViewreloadData()时可以获取数据