我无法在 UICollectionView 中显示图像

I can't display images in UICollectionView

我想在collectionView中显示UIImage

从 Json 数据中获取图像路径。

图片路径是从之前赋值的变量中获取的 我正在尝试显示图片,但无法获取。

API 正在工作。

但是我试图输出它来检查变量的值var photo = [Stores.photos]?但是它没有显示在控制台上

此外,如果您直接应用 imageURL,而不是从变量中应用,图像将会显示。 如何为 var photo = [Stores.photos]?

赋值

StorePhotoCollectionView

class StorePhotoViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

var store_id = ""

var store : [Store]?
var photo : [Store.photos]?

@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var storePhotoUIView: UIView!


override func viewDidLoad() {
    super.viewDidLoad()

    //Request API
    let url = URL(string: "http://localhost:8000/store/api?store_id=" + store_id)
    let request = URLRequest(url: url!)
    let session = URLSession.shared

    let encoder: JSONEncoder = JSONEncoder()
    encoder.dateEncodingStrategy = .iso8601
    encoder.outputFormatting = .prettyPrinted

    session.dataTask(with: request){(data, response, error)in if error == nil,
        let data = data,
        let response = response as? HTTPURLResponse{

        let decoder: JSONDecoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        do {

            let json = try decoder.decode(Store.self, from: data)


            self.store = [json]
            self.photo = json.photos

            DispatchQueue.main.async {
                self.nameLabel.text = json.name
                self.locationLabel.text = json.location
            }

        } catch {
            print("error:", error.localizedDescription)

        }

        }

        }.resume()

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    //UIView Corner redius
    let uiViewPath = UIBezierPath(roundedRect: storePhotoUIView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 8, height: 8))
    let uiViewMask = CAShapeLayer()
    uiViewMask.path = uiViewPath.cgPath
    storePhotoUIView.layer.mask = uiViewMask
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

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

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


    let imageCell : UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath)
    let imageView = imageCell.contentView.viewWithTag(1) as! UIImageView

    print("asssss")

    let imageURL = URL(string:  "http://127.0.0.1:8000/photos/" + photo![indexPath.row].path)
    if imageURL == nil {
        print("nil")
    }else{
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: imageURL!)
            if let data = data{
                let image = UIImage(data: data)
                DispatchQueue.main.async {
                    imageView.image = image
                }
            }
        }
    }
    return imageCell
}

}

调用dispatchque后,尝试添加.resume()

DispatchQueue.global().async {
        let data = try? Data(contentsOf: imageURL!)
        if let data = data{
            let image = UIImage(data: data)
            DispatchQueue.main.async {
                imageView.image = image
            }
        }
    }.resume()
}

如果我是你而不是手动处理响应等我会简单地使用一个开源库 https://github.com/onevcat/Kingfisher

使用非常简单,您无需自己处理这些操作:

imageView.kf.setImage(with: URL(string: "your_url_here"))

您忘记刷新您的集合视图,最初为您的集合视图创建对象

@IBOutlet weak var yourcollectionView: UICollectionView!

辅助你的主线程 UI 更新,刷新 UICollectionView

DispatchQueue.main.async {
            self.nameLabel.text = json.name
            self.locationLabel.text = json.location
            yourcollectionView.reloadData()

        }

最后从服务器加载图像,在这里你正在做主线程调用,它会冻结你的应用程序,图像显示过程见this example