在swift中解析json在UICollectionViewCell中

在swift中解析json在UICollectionViewCell中

问题描述:

我想解析UICollectionviewCell中的JSON。我有一个collectionViewController与两个UICollectionviewCell。在collectionViewController第一个单元格作背景滚动,在第二个我想解析JSON。代码中没有错误,这是我的JSON代码。在swift中解析json在UICollectionViewCell中

var oCategoryFilter: CategoryFilter? { 
    didSet { 

     if let name = oCategoryFilter?.totalItem { 
      totalItemLabel.text = name 
     } 

     appsCollectionView.reloadData() 
    } 
} 

var arrProduct: [Product]? 

func getPropductListByCategory(){ 

    let category_id:String; 

    category_id = "21" 

    let url = URL(string: UtilityController.BASE_URL+"/products/"+category_id) 

    URLSession.shared.dataTask(with:url!) { (urlContent, response, error) in 
     if error != nil { 
      print(error) 

     } 
     else { 
      do { 
       let json = try JSONSerialization.jsonObject(with: urlContent!) as! [String:Any] 

       print(json) 

       let items = json["categories"] as? [[String: Any]] ?? [] 

       items.forEach { item in 

        let oProduct = Product() 
        //oProduct.id = item["id"] as? String 
        oProduct.image = item["image"] as? String 
        oProduct.name = item["name"] as? String 
        oProduct.ar_name = item["ar_name"] as? String 
        //oProduct.description = item["description"] as? String 
        oProduct.ar_description = item["ar_description"] as? String 
        oProduct.price = item["price"] as? String 
        oProduct.quantity = item["quantity"] as? String 
        oProduct.is_featured = item["is_featured"] as? String 
        oProduct.seller_id = item["seller_id"] as? String 
        oProduct.payment_required = item["payment_required"] as? String 
        oProduct.is_editors_choice = item["is_editors_choice"] as? String 
        oProduct.created_at = item["created_at"] as? String 
        oProduct.updated_at = item["updated_at"] as? String 

        self.arrProduct?.append(oProduct) 
       } 
       print(url) 
      } catch let error as NSError { 
       print(error) 
      } 
     } 

     DispatchQueue.main.async(execute: { 
      self.appsCollectionView.reloadData() 
     }) 


     }.resume() 
} 

你什么时候打电话给你的功能?您应该在CollectionView中调用该方法,当它加载每个单元格时,但这样做非常糟糕,因为每次滚动或重新加载CollectionView时都会再次解析。

你应该在一个特殊的类中解析,由集合视图调用,最后把解析对象发送给单元。