UICollectionViewCells 在使用 JSONDecoder 时显示为空

UICollectionViewCells appear empty while using JSONDecoder

我正在尝试在 UICollectionView 中使用解码后的 json 数据。我遇到的问题是单元格显示为空白。

当我使用 print(playing)print(searchs) 打印解码结果时,控制台会显示正确的 json 数据。问题是,当我将它变成 var = nowPlaying = [Results]() 时,除了 [] 之外,没有任何内容打印到控制台。

如果我尝试使用 var nowPlaying = [NowPlaying](),我会收到 Value of type 'FilmsViewController.NowPlaying' has no member title 作为 let title = film.title 的错误,并且控制台仅显示 []

我要解决的是如何在 UICollectionView 中显示数据。

代码:

import UIKit
import AFNetworking


class FilmsViewController: UIViewController, UICollectionViewDelegate, 
UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, 
UISearchBarDelegate, UITextFieldDelegate {

var nowPlaying = [Results]()

struct NowPlaying: Codable {
    let results: [Results]
}

struct Results: Codable {
    let title: String
    let poster_path: String?
    let id: Int
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.filmsCollection.dataSource = self
    self.filmsCollection.delegate = self

    newFilms()

    print(nowPlaying)
    print(nowPlaying.count)


}

func collectionView(_ _collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if searchBar.text != "" {
        return searchTitle.count
    } else {
        return nowPlaying.count
    }
}


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

        let cell = filmsCollection.dequeueReusableCell(withReuseIdentifier: "filmCell", for: indexPath) as! FilmCell

        if searchBar.text == "" {
            let film = nowPlaying[indexPath.row]
            let title = film.title
            let poster = film.poster_path
            let baseUrl = "http://image.tmdb.org/t/p/w500"
            let imageUrl = URL(string: baseUrl + poster!)
            cell.titleLabel.text = title
            cell.posterImage.setImageWith(imageUrl!)
        }

        return cell


}

   ////////Parse Film API//////////////////


    func newFilms() {

        let apiKey = ""
        let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)&language=en-US&page=1")
        let request = URLRequest(
            url: url! as URL,
            cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData,
            timeoutInterval: 10 )

        let session = URLSession (
            configuration: URLSessionConfiguration.default,
            delegate: nil,
            delegateQueue: OperationQueue.main
        )

        let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
            if let data = data {
                do {
                    let playing = [try! JSONDecoder().decode(NowPlaying.self, from: data)]
                    print(playing)
                    self.filmsCollection.reloadData()

                }

            }

            self.filmsCollection.reloadData()

        })


        task.resume()

    }

    //////////End Parse Film API///////////////////

JSON Api 数据:

{
results: [
{
vote_count: 549,
id: 335983,
video: false,
vote_average: 6.7,
title: "Venom",
popularity: 692.629,
poster_path: "/2uNW4WbgBXL25BAbXGLnLqX71Sw.jpg",
original_language: "en",
original_title: "Venom",
genre_ids: [
27,
878,
28,
53
],
backdrop_path: "/VuukZLgaCrho2Ar8Scl9HtV3yD.jpg",
adult: false,
overview: "When Eddie Brock acquires the powers of a symbiote, he will have to 
release his alter-ego “Venom” to save his life.",
release_date: "2018-10-03"
},
{
vote_count: 2515,
id: 363088,
video: false,
vote_average: 6.9,
title: "Ant-Man and the Wasp",
popularity: 247.334,
poster_path: "/rv1AWImgx386ULjcf62VYaW8zSt.jpg",
original_language: "en",
original_title: "Ant-Man and the Wasp",
genre_ids: [
28,
12,
35,
878,
10751,
10749
],
backdrop_path: "/6P3c80EOm7BodndGBUAJHHsHKrp.jpg",
adult: false,
overview: "Just when his time under house arrest is about to end, Scott Lang 
puts again his freedom at risk to help Hope van Dyne and Dr. Hank Pym dive into 
the quantum realm and try to accomplish, against time and any chance of 
success, a very dangerous rescue mission.",
release_date: "2018-07-04"
},

您在 var nowPlaying = [Results]() 中设置的数据有误。

你也可以这样走:

let playing = try! JSONDecoder().decode(NowPlaying.self, from: data)
print(playing)
self.nowPlaying = playing.results
self.filmsCollection.reloadData()

并且数据将填充到 array

或者你也可以这样做:

var nowPlaying : NowPlaying!

在api方法中:

self.nowPlaying = try! JSONDecoder().decode(NowPlaying.self, from: data)
self.filmsCollection.reloadData()

然后在 cellForItemAt:

let film = nowPlaying.results[indexPath.row]

我没有编译过代码,我也不知道json数据。但是我是根据我从问题中的理解给出的解决方案。

希望对你有用。