Я пытаюсь использовать мои декодированные данные json в UICollectionView.У меня проблема в том, что клетки отображаются пустыми.
Когда я печатаю результаты декодирования с использованием 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"
},