iOS-JSON数据到CollectionView

时间:2018-11-12 01:16:01

标签: ios json swift

我正在尝试从API下载资源,并让它们填充集合视图。我在将下载的JSON数据发送到collectionview时遇到问题。数据下载正常,但是我无法将其连接/发送到我的collectionviewcells。我想念什么?

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var productCollectionView: UICollectionView!

var products = [Product]()


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return products.count

}

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

    let product = products[indexPath.row]
    let productViewModel = ProductViewModel(product: product)

    let imageData = NSData(contentsOf: productViewModel.productPhoto.standardizedFileURL)
    let productImage = UIImage(data: imageData! as Data)

    productCell.productName?.text = productViewModel.productTitle
    productCell.productImage?.image = productImage

    return productCell
}

func fetchProductData(){
    getProducts(for: 1){ (result) in

        switch result{

        case .success(let product):
            self.products = product

            print(product)

        case .failure(let error):
            fatalError("error: \(error.localizedDescription)")

        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    fetchProductData()
    productCollectionView.dataSource = self

    productCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "productCell")


}

}

0 个答案:

没有答案