Swift:除了image之外,所有东西都是从collectionViewCell中的web加载的

时间:2017-09-10 07:30:20

标签: ios json swift swift3 uicollectionview

我在UICollectionViewCell中放了一个sliderCollectionViewController,现在所有内容都是从web正常加载而没有图像。但我没有得到任何关于错误的消息

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

2 个答案:

答案 0 :(得分:0)

问题是你做了:

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

但all_images不是字符串,它是你在json中可以看到的字典。

您必须访问all_images的关键图像才能正确显示。

看到这个: indexOf

你可以试试这个:

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

答案 1 :(得分:0)

all_images的值是一个字典数组。如果要提取所有image值,请使用flatMap函数

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

但请注意,键image的值是URL的字符串表示形式。