如何快速将json图像添加到collectionView单元格而没有nil?

问题描述 投票:0回答:1

我有一个UICollectionViewUIImageView。我正在从json获取所有图像。如果我打印json图像,它可以工作,但是我无法在cellForItemAtIndexPath中添加这些json图像,但是得到的结果是零。

如何检查图像URL是否不为零,然后将其添加到收集单元格中?

这是我的代码:

import UIKit
import SDWebImage
struct apiValues {

var imgUrls: String?
var labelText: String?
init(icon: String, tpe: String) {
    self.imgUrls = icon
    self.labelText = tpe
}
}

class collectioViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {

@IBOutlet weak var collectionView: UICollectionView!

var itemsArray = [apiValues]()

override func viewDidLoad() {
    super.viewDidLoad()
    homeServiceCall()

    collectionView.delegate = self
    collectionView.dataSource = self
}

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

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell

    let aData = itemsArray[indexPath.row]
    cell.paymentLabel.text = aData.labelText

    print("tableview collection images \(String(describing: aData.imgUrls))")
    cell.paymentImage.sd_setImage(with: URL(string:aData.imgUrls!), placeholderImage: UIImage(named: "GVMC_icon"))



    return cell
}
//MARK:- Service-call

func homeServiceCall(){

    let urlStr = "https://dev.anyemi.com/webservices/anyemi/getfinancer"
    let url = URL(string: urlStr)
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in

    guard let respData = data else {
        return
    }
    guard error == nil else {
        print("error")
        return
    }
    do{
       let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
       let finArray = jsonObj["financer"] as! [[String: Any]]

       for financer in finArray {

           let id = financer["id"] as? String
           let pic = financer["icon"] as? String
           let typeName = financer["tpe"] as! String
           print("home financer id \(String(describing: id))")
           print("the icons \(String(describing: pic))")
           self.itemsArray.append(apiValues(icon: pic ?? "", tpe: typeName))
       }
    DispatchQueue.main.async {
            self.collectionView.reloadData()
        }
   }
   catch {
           print("catch error")
       }
   }).resume()
}
}
ios json swift uicollectionview uiimageview
1个回答
0
投票

您可能在错误的时间重新加载了收藏集。

尝试此代码:

import UIKit
import SDWebImage
struct apiValues {

    var imgUrls: String?
    var labelText: String?
    init(icon: String, tpe: String) {
        self.imgUrls = icon
        self.labelText = tpe
    }
}

class collectioViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var collectionView: UICollectionView!

    var itemsArray = [apiValues]()

    override func viewDidLoad() {
        super.viewDidLoad()
        homeServiceCall()

        collectionView.delegate = self
        collectionView.dataSource = self
    }

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

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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell

        let aData = itemsArray[indexPath.row]
        cell.paymentLabel.text = aData.labelText

        print("tableview collection images \(String(describing: aData.imgUrls))")
        cell.paymentImage.sd_setImage(with: URL(string:aData.imgUrls!), placeholderImage: UIImage(named: "GVMC_icon"))



        return cell
    }
    //MARK:- Service-call

    func homeServiceCall(){

        let urlStr = "https://dev.anyemi.com/webservices/anyemi/getfinancer"
        let url = URL(string: urlStr)
        URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in

        guard let respData = data else {
            return
        }
        guard error == nil else {
            print("error")
            return
        }
        do{
           let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
           let finArray = jsonObj["financer"] as! [[String: Any]]

           for financer in finArray {

               let id = financer["id"] as? String
               let pic = financer["icon"] as? String
               let typeName = financer["tpe"] as! String
               print("home financer id \(String(describing: id))")
               print("the icons \(String(describing: pic))")
               self.itemsArray.append(apiValues(icon: pic ?? "", tpe: typeName))
           }
        DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
       }
       catch {
               print("catch error")
           }
       }).resume()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.