2017-07-17 61 views
0

我想解析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() 
} 

回答

1

你什麼時候打電話給你的功能?您應該在CollectionView中調用該方法,當它加載每個單元格時,但這樣做非常糟糕,因爲每次滾動或重新加載CollectionView時都會再次解析。

你應該在一個特殊的類中解析,由集合視圖調用,最後把解析對象發送給單元。