0

I'm making a mini pokedex app, and within the view controller, I was hoping to include a description of each pokemon from pokeapi.co, but when I run my code, it remains empty text. Here's the function:

func loadDesc() {
    URLSession.shared.dataTask(with: url2!) { (data, response, error) in
        guard let data = data else {
            return
        }
        do {
            let result2 = try JSONDecoder().decode(PokemonDescResult.self, from: data)
                for description in result2.flavor_text_entries {
                    self.pokeDesc.text = description.flavor_text
                }
        }
        catch let error {
            print(error)
        }
    }.resume()
}

I'm also pretty knew to Swift and stackoverflow, so if you need ant more code to understand, let me know. Thanks!

meematzzz
  • 3
  • 3
  • Where are you trying to access the data? Have you looked at [this](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function)? – Paulw11 Oct 29 '20 at 01:29
  • @Paulw11 I don't really understand that. I'm trying to access the data from another line of code before the func, `let url2 = URL(string: "https://pokeapi.co/api/v2/pokemon-species?limit=151")` - so that url is where I'm getting my data – meematzzz Oct 29 '20 at 01:38
  • The `dataTask` completes asynchronously; That is it takes some time for the data to come back from the network. You can only access the data in the completion handler for the task. You would typically pass a closure to `loadDesc` and in that closure you can do whatever you need to with the data. – Paulw11 Oct 29 '20 at 02:53
  • See also http://www.programmingios.net/what-asynchronous-means/ – Paulw11 Oct 29 '20 at 02:55

0 Answers0