0

I am looking to make multiple API calls using swift to get my data from the TMDB API. I have created the struct and the code I am using is this:

import Foundation

public class LoadTMDBMovies{
  
  // Create an array of TMDBMovies data to store the results
  var moviesList = [MoviesIndividual]()
  let tmdbId = LoadLinksData().linksJSON
  
  func fetch(){
    for tmdbIds in tmdbId{
      let id = tmdbIds.tmdbId
      let api = "https://api.themoviedb.org/3/movie/" + String(id) + "?api_key="
      let url = URL(string: api)!
      let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        // get the data
        guard let data = data, error == nil else {return}
        do{
          let moviesData = try JSONDecoder().decode(MoviesIndividual.self, from: data)
          self.moviesList.append(moviesData)
        }
        catch{
          let error = error
          print(error.localizedDescription)
        }
      };task.resume()
    }
  }
  
}

I am trying to loop through all the items in my array get the TMDB Id and replace it in the URL where necessary. This doesn't give me an error when I run it just a warning that my tmdbId was never used and prints a count of 0 when I tested it out.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • `print(error.localizedDescription)` => `print(error)`, that's better for debugging. Now, it's unclear, is `tmdbId` empty? Could you print it at the start of `fetch()`? "that my tmdbId was never used " which line exactly? – Larme Apr 09 '21 at 12:32
  • I think we need more info as @Larme asked. Maybe you can also check if [this](https://stackoverflow.com/questions/35906568/wait-until-swift-for-loop-with-asynchronous-network-requests-finishes-executing) answers your question or not. – Burak Akkaş Apr 09 '21 at 12:52
  • Where do you print the count? – Joakim Danielson Apr 09 '21 at 13:10
  • Thank you for your reply. Okay so firstly it doesn't give me any errors. tmdbId is not empty because I've printed it before to check – dean miller Apr 09 '21 at 14:34
  • " prints a count of 0 when I tested it out": WHERE is that print? It's unclear if you are missing an asynchrone concept or not. – Larme Apr 09 '21 at 15:17
  • It’s not easy to get any information here :) I would suggest the following, add a print just before the api call, like `print(api)`, and then add a print after the decoding, like `print(moviesData)` (or for less clutter only one property from the type). Do you get the expected output in the console or not? If not, what is missing? – Joakim Danielson Apr 09 '21 at 15:52
  • Okay, I made the count calls in my view controller script. I've just done some debugging with a few print statements. It seems to get the url fine but just doesn't do anything when it gets to the decoder part. – dean miller Apr 09 '21 at 17:45
  • So your api calls doesn’t return any data, maybe `error` isn’t nil? – Joakim Danielson Apr 10 '21 at 06:36

0 Answers0