UICollectionViewCells在使用JSONDecoder时显示为空

时间:2018-10-09 01:40:47

标签: ios swift uicollectionview jsondecoder

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

当我使用print(playing)print(searchs)打印解码结果时,控制台将显示正确的json数据。问题是当我将其变成var = nowPlaying = [Results]()时,除了[]以外,什么都没有打印到控制台。

如果我尝试使用var nowPlaying = [NowPlaying](),则会收到错误Value of type 'FilmsViewController.NowPlaying' has no member titlelet 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"
},

1 个答案:

答案 0 :(得分:1)

您在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数据。但是我根据问题的理解给出解决方案。

希望它对您有用。