Search code examples
iosjsonswiftparsingjsondecoder

How to parse iTunes API in swift 4?


I need to do an app used to search through the iTunes API.

But I can't use any library so it's different than what I'm used to.

With this URL I'm supposed to get the first result for "Instagram" search through the software: "https://itunes.apple.com/search?entity=software&country=fr&limit=1&term=instagram"

I try to get the results with this part of code:

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()

but it doesn't work and always catch an error.

Here is the JSON I can get:

{
    "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
    }]
}

And the models I use:

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

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

I tried to solve my problem with other topics about this feature but I can't fix it.


Solution

  • The error was in the model App, I wrote String for an integer expected value.

    You can delete that question.