Obtain data from the Mock API - DevOli/Marvel-chars GitHub Wiki

Decoding JSON Data

Using the quicktype tool (https://app.quicktype.io), we can pass a JSON object and generate the Swift code to correctly obtain the Get Request Data from the URLSession (Note: in the tool change the name to 'Marvel').

let decoder = JSONDecoder()
guard let safeData = data else {
  return
}
let marvelAPI = try? decoder.decode(Marvel.self, from: safeData)
guard let results = marvelAPI?[0] else {
  return
}

Parsing to Models

We need to create Models for Characters and Categories. The Categories should have an array of Characters. We can get an array of our Character Model from the decoding results.

let heroes = self?.getCharactersFrom(category: results.heroes)

func getCharactersFrom(category: [Alien]) -> [CharacterModel]{
  var characters: [CharacterModel] = []
  for character in category {
    characters.append(CharacterModel(character: character))
  }
  return characters
}

Example of how to get one character in a category

The Category Model has a method to get a Character Model with a passing index. With a Character Model you can access all properties shown in the JSON. The Category Model also has a category property for its name and a characters count property if necessary.

let hero = heroes.getCharacter(at: heroes.charactersCount - 1)
print(hero)

func getCharacter(at index: Int) -> CharacterModel {
  return self.characters[index]
}

API URL: https://619d463f131c600017088e71.mockapi.io/api/v1/characters