如何在 swift 4 中解析 iTunes API?

How to parse iTunes API in swift 4?

我需要做一个用于通过 iTunes 进行搜索的应用程序 API。

但是我不能使用任何库,所以它与我习惯的不同。

有了这个 URL 我应该会得到 "Instagram" 通过软件搜索的第一个结果:“https://itunes.apple.com/search?entity=software&country=fr&limit=1&term=instagram

我尝试用这部分代码得到结果:

let url = URL(string: "https://itunes.apple.com/search?entity=software&country=fr&limit=1&term=instagram")!

URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let data = data else { return }
    do {
        let decodedResponse = try JSONDecoder().decode(iTunesResponse.self, from: data)
    } catch let error {
        print("Failed to load: \(error.localizedDescription)")
    }
}.resume()

但是它不起作用,总是会出错。

这里是JSON我可以得到:

{
    "resultCount": 1,
    "results": [{
        "screenshotUrls": ["https://is2-ssl.mzstatic.com/image/thumb/Purple123/v4/e9/d2/bf/e9d2bf85-7c32-0ac3-cc1f-e7160abbb8d6/source/392x696bb.jpg"],
        ...
        "userRatingCount": 1697595
    }]
}

以及我使用的机型:

struct iTunesResponse: Decodable {
    let resultCount: Int?
    let results: [App]?
}

struct App: Decodable {
 let isGameCenterEnabled: Bool?
 let screenshotUrls: [String]?
 ...
 let userRatingCount: Int?
}

我尝试用有关此功能的其他主题来解决我的问题,但我无法修复它。

请检查响应关闭中的空数据计数。

guard let data = data, data.count > 0 else { return }

有时,数据可以是非零和空数据。

错误在模型应用程序中,我为整数期望值编写了字符串。

你可以删除那个问题。