TMDb API调用-Swift [英] TMDb api call - Swift

查看:498
本文介绍了TMDb API调用-Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用 TMDb Api 来获取数组类型的电影我在要访问的许多属性(例如"vote_count","poster_path"和"vote_average")上都返回零".

I'm calling the TMDb Api to get an array of movies by genre. I'm getting 'nil' back on many of the properties I want to access such as "vote_count", "poster_path" and "vote_average".

如果我在浏览器中调用api,则会获得所有预期的属性.

If I call the api in a browser I get all of the properties as expected.

这是我的模特:

import Foundation

// MARK: - MovieList
struct MovieList: Codable {
    let page: Int
    let totalResults: Int?
    let totalPages: Int?
    let results: [Result]

    enum CodingKeys: String, CodingKey {
        case page
        case totalResults = "total_results"
        case totalPages = "total_pages"
        case results
    }
}

// MARK: - Result
struct Result: Codable {
    let popularity: Double?
    let voteCount: Int?
    let video: Bool?
    let posterPath: String?
    let id: Int?
    let adult: Bool?
    let backdropPath: String?
    let originalLanguage: OriginalLanguage?
    let originalTitle: String?
    let genreIDS: [Int]?
    let title: String?
    let voteAverage: Double?
    let overview, releaseDate: String?

    enum CodingKeys: String, CodingKey {
        case popularity
        case voteCount = "vote_count"
        case video
        case posterPath = "poster_path"
        case id, adult
        case backdropPath = "backdrop_path"
        case originalLanguage = "original_language"
        case originalTitle = "original_title"
        case genreIDS = "genre_ids"
        case title
        case voteAverage = "vote_average"
        case overview
        case releaseDate = "release_date"
    }
}

enum OriginalLanguage: String, Codable {
    case en = "en"
    case es = "es"
}

这是网络电话:

func getMovieDetails(movie: Int, completion: @escaping (Result?) -> ()) {

        guard let url = URL(string: "https://api.themoviedb.org/3/movie/157336?api_key=6228bff945f7bd2m18c04fc3839829c0") else {
            fatalError("Invalid URL")
        }

            let config = URLSessionConfiguration.default
            let session = URLSession(configuration: config)

            let task = session.dataTask(with: url) { data, response, error in

                // Check for errors
                guard error == nil else {
                    print ("error: \(error!)")
                    return
                }
                // Check that data has been returned
                guard let data = data else {
                    print("No data")
                    return
                }

                do {

                    let decoder = JSONDecoder()
                    decoder.keyDecodingStrategy = .convertFromSnakeCase
                    let movieDetails = try decoder.decode(Result.self, from: data)

                    DispatchQueue.main.async {

                       completion(movieDetails)
                        print(movieDetails)

                    }

                } catch let err {
                    print("Err", err)
                }
            }
            // execute the HTTP request
            task.resume()
        }
    }

这是响应:

MovieList(page: 1, totalResults: nil, totalPages: nil, results: [QuickFlicks.Result(popularity: Optional(171.78), voteCount: nil, video: Optional(false), posterPath: nil, id: Optional(454626), adult: Optional(false), backdropPath: nil, originalLanguage: nil, originalTitle: nil, genreIDS: nil, title: Optional("Sonic the Hedgehog"), voteAverage: nil, overview: Optional("Based on the global blockbuster videogame franchise from Sega, Sonic the Hedgehog tells the story of the world’s speediest hedgehog as he embraces his new home on Earth. In this live-action adventure comedy, Sonic and his new best friend team up to defend the planet from the evil genius Dr. Robotnik and his plans for world domination."), releaseDate: nil)])

任何帮助将不胜感激.谢谢.

Any help would be appreciated. Thank you.

推荐答案

您正在向解码器给出矛盾的指令,首先您拥有CodingKeys枚举,该枚举说例如应该从poster_path中读取posterPath属性.键,但是您设置了keyDecodingStrategy = .convertFromSnakeCase,这意味着解码器首先将键poster_path转换为posterPath ,然后尝试将键与属性匹配.

You are giving contradicting instructions to the decoder, first you have the CodingKeys enum that say for instance that the posterPath property should be read from the poster_path key but then you set keyDecodingStrategy = .convertFromSnakeCase which means that the decoder first translates the key poster_path to posterPath before trying to match the key to a property.

因此,请删除decoder.keyDecodingStrategy = .convertFromSnakeCase或删除CodingKeys枚举

So either remove decoder.keyDecodingStrategy = .convertFromSnakeCase or remove the CodingKeys enum

这篇关于TMDb API调用-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆