ios:所有数据都从 json webrequest 加载,除了 Slider CollectionViewCell

ios: All data is loading from json web request except SliderCollectionViewCell

我在 UICollectionViewCell 中有 sliderCollectionViewController,尝试从 json 网络加载数据,加载所有数据时没有图像。在这里,我喜欢加载 slideCollectionViewCell 中的图像,这些图像是在 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 { [=12=]["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 网络数据

您应该使用 UIImageView 子类 CustomImageView

中的方法

所以而不是

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

试试这个:

cell.imageView.loadImageUsingUrlString(imageName)

在你cellForItem方法DescriptionCell