1

I have sliderCollectionViewController in UICollectionViewCell, try to loading data from json web, all data is loading without image. Here I like to load images in slideCollectionViewCell which created in a collectionViewCell.

import UIKit

import Foundation


**DescriptionObject**

`class Description: NSObject {

    var id: Int?
    var product_id: Int?

    var myDescription: String?
   var product_description: String?

    var all_images: [String]?


}

**DescriptionCollectionViewController with slideCollectionViewController**

class DescriptionCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout{



    var arrDescription = [Description]()

   **json request**

    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

                        if let allImages = dt["all_images"] as? [[String:Any]] {
                            oProduct.all_images = allImages.flatMap { $0["image"] 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()
    }



    fileprivate let cellId = "cellId"
    fileprivate 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

            slideCollectionView.reloadData()
        }
    }

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



        setupCell()


    }

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




    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
    }()



    fileprivate 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
    }()



    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
    }


}


**SlideCollectionViewCell**

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)


    }



}`

**Image Extension**

let imageCache = NSCache<AnyObject, AnyObject>()

class CustomImageView: UIImageView {

    var imageUrlString: String?

    func loadImageUsingUrlString(_ urlString: String) {

        imageUrlString = urlString

        guard let urlEncoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            print("Encoding not done")
            return
        }

        let url = URL(string: urlEncoded)

        image = nil

        if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
            self.image = imageFromCache
            return
        }


        if let url = url {
            URLSession.shared.dataTask(with: url, completionHandler: {(myData, respones, error) in

                if error != nil {
                    print(error ?? 0)
                    return
                }

                if let myData = myData {
                    DispatchQueue.main.async(execute: {

                        let imageToCache = UIImage(data: myData)

                        if self.imageUrlString == urlString {
                            self.image = imageToCache
                        }

                        if let imageToCache = imageToCache {
                            imageCache.setObject(imageToCache, forKey: urlString as AnyObject)
                        }
                    })
                }

            }).resume()
        }
    }

}

json web data

enter image description here

Quiet Islet
  • 536
  • 1
  • 8
  • 28
  • If you add `descriptionOb?.all_images` before `if let` then does it print the images string or not? – 3stud1ant3 Sep 11 '17 at 04:01
  • @3stud1ant3 it have to put in which part – Quiet Islet Sep 11 '17 at 04:02
  • in `cellForItemAt ` method in `DescriptionCell` class where you are setting the image – 3stud1ant3 Sep 11 '17 at 04:03
  • @3stud1ant3 sorry i do not understand your meaning. it is code in DescriptionCell. `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 }` – Quiet Islet Sep 11 '17 at 04:09
  • 1
    o my bad, sorry , I meant please add `print(descriptionOb?.all_images)` before `if` in the above code and see if it prints the images string? – 3stud1ant3 Sep 11 '17 at 04:12
  • @3stud1ant3 image prints in console – Quiet Islet Sep 11 '17 at 04:15
  • @3stud1ant3 i could not reply you in chanRoom, i do not know why – Quiet Islet Sep 11 '17 at 04:19
  • Ok , can you show what does it print? – 3stud1ant3 Sep 11 '17 at 04:19
  • @3stud1ant3 i got this message in console `Optional(["http://......./public/uploads/media/1499841681c700x420.jpg", "http://......../public/uploads/media/1499841694c700x420 (1).jpg", "http://......../public/uploads/media/1499841694c700x420 (2).jpg", "http://......./public/uploads/media/1499841694c700x420 (3).jpg"])` – Quiet Islet Sep 11 '17 at 04:20
  • please show the code for `CustomImageView` – 3stud1ant3 Sep 11 '17 at 04:40
  • @3stud1ant3 `CustomImageView` code i post with my question in `Image Extension` part. those is in end of my code before json png file. please check again my codes. – Quiet Islet Sep 11 '17 at 04:44
  • 1
    ok , instead of `cell.imageView.image = UIImage(named: imageName)` try this: `cell.imageView.loadImageUsingUrlString(imageName)` in you `cellForItem` method and please tell me the response – 3stud1ant3 Sep 11 '17 at 04:46
  • @3stud1ant3 Friend! can you come to this link please. this problem still is not solve https://stackoverflow.com/questions/46126908/swift-error-in-didselectitematindexpath-function-of-listtableviewcontroller-whe – Quiet Islet Sep 11 '17 at 05:09
  • this question is deleted, that you linked – 3stud1ant3 Sep 11 '17 at 07:50
  • @3stud1ant3 this is new link of my question please come to there. i need your help. https://stackoverflow.com/questions/46149881/swift-didselectitematindexpath-function-not-work-of-json/46150135?noredirect=1#comment79265464_46150135 – Quiet Islet Sep 11 '17 at 10:01

1 Answers1

1

You should use the method in UIImageView subclass CustomImageView

so instead of

cell.imageView.image = UIImage(named: imageName)

try this:

cell.imageView.loadImageUsingUrlString(imageName)

in you cellForItem method of DescriptionCell

3stud1ant3
  • 3,586
  • 2
  • 12
  • 15