CS50 iOS Track 3: Dynamic Data in the Pokedex App

Jun 14, 2024

Lecture: Dynamic Data in the Pokédex App

Introduction

  • Focus on bringing dynamic data from the internet using APIs
  • API: Application Programming Interface

Understanding APIs

  • APIs allow you to use code written by someone else
  • Making web requests to retrieve Pokémon data
  • Data format: JSON (JavaScript Object Notation)

JSON Format

  • JSON resembles a Swift dictionary
  • Syntax: {key: value} pairs
  • Key-value pairs may contain strings, arrays, numbers, etc.
  • Example:
    {
      "course": "cs50",
      "tracks": ["mobile", "web", "games"],
      "year": 2019
    }
    

Swift Constructs

Try, Catch

  • Handles exceptions
  • Syntax:
    do {
      let result = try someFunction()
    } catch let error {
      print(error)
    }
    

Closures

  • Anonymous inline functions
  • Syntax:
    let reversed = names.sorted { (s1: String, s2: String) -> Bool in
      return s1 > s2
    }
    

Delegates

  • Attaching event handlers to objects
  • Example: Notifying when data is received

Using PokeAPI

  • Base URL: https://pokeapi.co/api/v2/
  • Fetching data (e.g. Pokémon Ditto example)

Fetching Data in iOS

Removing Hardcoded Data

  • Remove static data assignments from the view controllers

Fetching API Data

  • Use URL and URLSession classes
  • Example URL: https://pokeapi.co/api/v2/pokemon?limit=151
  • Syntax for making a web request:
    let url = URL(string: "https://pokeapi.co/api/v2/pokemon?limit=151")!
    URLSession.shared.dataTask(with: url) { (data, response, error) in
      guard let data = data else { return }
      // Further processing
    }.resume()
    

Handling JSON Data

  • Decode JSON and map it to Swift structs
  • Create model structs conforming to Codable protocol
  • Example:
    struct Pokemon: Codable {
      let name: String
      let url: String
    }
    struct PokemonList: Codable {
      let results: [Pokemon]
    }
    

Viewing Data and Error Handling

  • Use do-try-catch to handle decoding errors
  • Reload data method to update UI on data retrieval
  • Remember to work on the main thread for UI updates:
    DispatchQueue.main.async {
      self.tableView.reloadData()
    }
    

API Usage in Detail View

Structs for Retrieved Data

  • Multiple levels of nested data
  • Create structs to represent nested API responses
    struct PokemonType: Codable {
      let name: String
      let url: String
    }
    struct PokemonTypeEntry: Codable {
      let slot: Int
      let type: PokemonType
    }
    struct PokemonData: Codable {
      let id: Int
      let types: [PokemonTypeEntry]
    }
    

Displaying Dynamic Data

  • Fetch detailed Pokémon data on selection
  • Set labels for type information programmatically
  • Clear placeholder text before updating based on API response

Conclusion

  • Replaced hardcoded data with dynamic API data in Pokédex app
  • API usage can enhance apps by leveraging different data sources
  • Introduction to image handling in the next session