我正在使用Alamofire从YTS api获取JSON数据并将它们加载到集合视图单元格上。它基本上是一个应用程序,提供有关即将上映的电影和最近添加的信息。这就是我使用Alamofire的方式。
func getMovieData(movieData: Data) {
DispatchQueue.global(qos: .background).async {
do {
var movieJSONData = try JSONSerialization.jsonObject(with: movieData, options: .mutableContainers) as! JSONStand
/*var name: String!
var desc: String!
var genre: [String]!*/
if let data = movieJSONData["data"] as? JSONStand {
if let movies = data["movies"] as! [JSONStand]! {
for i in 0..<movies.count {
let item = movies[i]
let movieName = item["title_english"] as! String
let movieDescription = item["synopsis"] as! String
let movieGenre = item["genres"] as! [String]
let movieYear = item["year"] as! Int
let movieRating = item["rating"] as! Double
let movieYoutubeTrailerCode = item["yt_trailer_code"] as! String
let movieRuntime = item["runtime"] as! Int
if let movieImage = item["medium_cover_image"] as? String {
let movieImageURL = URL(string: movieImage)
let movieImageData = NSData(contentsOf: movieImageURL!)
if movieImageData != nil {
self.mainMovieImage = UIImage(data: movieImageData as! Data)
}
else {
print("No image found")
}
if let torrents = item["torrents"] as? [JSONStand] {
for i in 0..<torrents.count {
let item = torrents[i]
let movieSize = item["size"] as! String
if movieSize.isEmpty == false {
self.movieSizeLabel = movieSize
}
else {
print("Couldn't get size")
}
}
}
}
DispatchQueue.main.async {
self.movie.append(Movie.init(names: movieName, descriptions: movieDescription, images: self.mainMovieImage, genres: movieGenre, years: movieYear, ratings: movieRating, sizes: self.movieSizeLabel, ytcodes: movieYoutubeTrailerCode, runtimes: movieRuntime))
self.collectionView?.reloadData()
}
}
}
}
}
catch {
var errorStringValue = error.localizedDescription
if error.localizedDescription.contains("correct") {
errorStringValue = "Internet connection unavailable, please connect to a wifi."
}
let alert = UIAlertController(title: "Oops", message: errorStringValue, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
这也就是我如何将它们加载到单元格上。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as UICollectionViewCell
cellImageView = cell.viewWithTag(2) as! UIImageView
cellMovieLabel = cell.viewWithTag(1) as! UILabel
movieLoadingIndicator = cell.viewWithTag(3) as! UIActivityIndicatorView
cellImageView.image = movie[indexPath.row].images
cellImageView.contentMode = .scaleAspectFit
cellMovieLabel.text = movie[indexPath.row].names
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.main.scale
return cell
}