Ios 带有服务器数据的UIcollectionview

Ios 带有服务器数据的UIcollectionview,ios,json,swift,uicollectionview,delegates,Ios,Json,Swift,Uicollectionview,Delegates,我正在尝试使用服务器数据创建collectionview我在 数组并打印它以确保返回数据 extension ViewController : DataModelDelegate { func didRecieveDataUpdate(data: Data) { let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])

我正在尝试使用服务器数据创建collectionview我在 数组并打印它以确保返回数据

    extension ViewController : DataModelDelegate {


        func didRecieveDataUpdate(data: Data) {

            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])

            // parse json array
            guard let jsonArray = responseJSON as? [[String: Any]]
                else {
                    return
            }
            for dic in jsonArray {
                self.listOfCategories.append(MCategories(dic))
            }
            print(self.listOfCategories[1].Name)
            print(self.listOfCategories.count)

        }
}

但此数组在collectionview()>int func中返回0

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cellcategory:CVC_Categories = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CVC_Categories
    cellcategory.setCategoryData(categories: listOfCategories[indexPath.row])
    return cellcategory
}
我称之为viewdidload()中的委托


收到数据后,需要与采集视图通信数据已更改。您可以通过调用集合视图上的
reloadData()
来实现这一点

因此,在你的情况下:

  func didRecieveDataUpdate(data: Data) {

    ....

    OperationQueue.main.async {
      self.collectionView.reloadData()
    }

  }
在此块中添加reloadData(),使其在主线程中运行

OperationQueue.main.addOperation ({
                self.cv_categories.reloadData()
            })

您必须在
direceivedataupdate
末尾调用集合视图上的
reloadData()
,并尝试在main queue DispatchQueue.main.async{}中重新加载集合视图
OperationQueue.main.addOperation ({
                self.cv_categories.reloadData()
            })