0

i put a sliderCollectionViewController in UICollectionViewCell, now everything is loading from web properly without image. but i am not getting any message about error

import UIKit
import Foundation

NSObject

class Description: NSObject {

    var id: Int?
    var product_id: Int?        
    var myDescription: String?      
    var all_images: [String]?    
    var product_description: String?      
}

DescriptionCollectionViewController

class DescriptionCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout{

    var arrDescription = [Description]()

    ** Networking Request api **

    func loadDescription(){

        ActivityIndicator.customActivityIndicatory(self.view, startAnimate: true)
        let url = URL(string: .......)

        URLSession.shared.dataTask(with:url!) { (urlContent, response, error) in
            if error != nil {
                print(error ?? 0)
            }
            else {
                 do {
                    let json = try JSONSerialization.jsonObject(with: urlContent!) as! [String:Any]

                    let myProducts = json["products"] as? [String: Any]
                    let myData = myProducts?["data"] as? [[String:Any]]

                    myData?.forEach { dt in

                        let oProduct = Description()
                        oProduct.id = dt["id"] as? Int
                        oProduct.product_id = dt["product_id"] as? Int

                        oProduct.myDescription = dt["description"] as? String
                        oProduct.product_description = dt["product_description"] as? String

                        oProduct.all_images = dt["all_images"] as? [String]

                        self.arrDescription.append(oProduct)
                    }                                           
                } catch let error as NSError {
                    print(error)
                }
            }

            DispatchQueue.main.async(execute: {
                ActivityIndicator.customActivityIndicatory(self.view, startAnimate: false)
                self.collectionView?.reloadData()
            })               
            }.resume()
    }


    let descriptionCellId = "descriptionCellid"

    override func viewDidLoad() {
        super.viewDidLoad()

        self.loadDescription()


        collectionView?.register(DescriptionCell.self, forCellWithReuseIdentifier: descriptionCellId)
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrDescription.count
    }


    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {            

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: descriptionCellId, for: indexPath) as! DescriptionCell

        cell.descriptionOb = arrDescription[indexPath.item]

        return cell            
    }
}

DescriptionCollectionViewCell

class DescriptionCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    var descriptionOb: Description? {
        didSet {

            descriptionTextView.text = descriptionOb?.myDescription

            couponTextView.text = descriptionOb?.product_description
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        setupCell()
    }

    let cellId = "cellId"

    lazy var slideCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.clear
        return cv
    }()


        let descriptionTextView: UITextView = {
            let textview = UITextView()
            textview.text = "Description is the pattern of development "

            return textview
        }()


        let couponTextView: UITextView = {

            let textview = UITextView()
                textview.text = "Description is the pattern of development "
            return textview
        }()

    func setupCell() {

                slideCollectionView.dataSource = self
                slideCollectionView.delegate = self

                 slideCollectionView.isPagingEnabled = true

                slideCollectionView.register(SlideCell.self, forCellWithReuseIdentifier: cellId)

                addSubview(slideCollectionView)
                addSubview(descriptionTextView)
                addSubview(couponTextView)            
            }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let count = descriptionOb?.all_images?.count{
            return count
        }
        return 0           
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SlideCell

        if let imageName = descriptionOb?.all_images?[indexPath.item]{
            cell.imageView.image = UIImage(named: imageName)
        }

        return cell
    }
}

SliderCell

class SlideCell: UICollectionViewCell{

    override init(frame: CGRect) {
        super.init(frame: frame)         
        setupCellSlider()         
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    let imageView: CustomImageView = {
        let iv = CustomImageView()
        iv.contentMode = .scaleAspectFill
        iv.image = UIImage(named: "defaultImage3")
        iv.backgroundColor = UIColor.green
        return iv
    }()


    func setupCellSlider() {     
        backgroundColor = .green
        addSubview(imageView)        
    } 
}

json web enter image description here

vadian
  • 274,689
  • 30
  • 353
  • 361
  • According to the JSON output the value for key `all_images` is an array of dictionaries rather than an array of strings. – vadian Sep 10 '17 at 07:43
  • @vadian yes friend! you are right. can you help me please. –  Sep 10 '17 at 07:45
  • The code to parse the other values is written very well so where is the problem? It's almost the same structure like the value for `data` – vadian Sep 10 '17 at 07:51
  • @vadian the problem is about all_images array of dictionaries, maybe i made a mistake to pass it, but i do not know where it is –  Sep 10 '17 at 09:10
  • Please add more information what (exactly) you are going to accomplish. – vadian Sep 10 '17 at 09:15
  • @vadian i want to put all_images values in SliderCollectionViewController's Cell. this SliderCollectionViewController added in DescriptionCollectionView Cell. –  Sep 10 '17 at 09:20
  • Just `values` is too broad. Each dictionary contains eight key/value pairs. – vadian Sep 10 '17 at 09:23
  • @vadian i just need to pass image value of all_images –  Sep 10 '17 at 09:24
  • I wrote an answer. – vadian Sep 10 '17 at 09:30

2 Answers2

0

The problem is that you did:

                oProduct.all_images = dt["all_images"] as? [String]

but all_images is not a string, it is a dictionary as you can see in your json.

You have to access the key image of all_images in order to show it properly.

See this: How to access deeply nested dictionaries in Swift

You can try this:

                oProduct.all_images = dt["all_images"]["image"] as? [String]
H S W
  • 6,310
  • 4
  • 25
  • 36
  • how to do it please, come to more details –  Sep 10 '17 at 07:48
  • i am getting error between two functions after use your code func numberOfItemsInSection { if let count = descriptionOb?.all_images?.count{ return count }} func cellForItemAt { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SlideCell if let imageName = descriptionOb?.all_images?[indexPath.item]{ cell.imageView.image = UIImage(named: imageName) } } –  Sep 10 '17 at 08:02
0

The value for key all_images is an array of dictionaries. If you want to extract all image values use the flatMap function

if let allImages = dt["all_images"] as? [[String:Any]] {
    oProduct.all_images = allImages.flatMap { $0["image"] as? String }
}

But consider that the value for key image is the string representation of an URL.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • thanks for your code, all error are gone after use your code. now slide.count is ok, but image still do not show. it think i have to add some code more to solve this problem. can you figure it please? –  Sep 10 '17 at 10:05
  • It depends on where the images are located. Your code implies that the images are located in the bundle, but the value `image` implies that the images are located on a (local) server. Programming is a very precise subject. If the latter is true you need an URL loading system including a cache which is beyond this question. – vadian Sep 10 '17 at 10:06
  • i added my two error image and imageView extension in new comment. please try to check it –  Sep 10 '17 at 10:26