0

I am coding a view controller that gets a JSON array of latest released films and displays them in the class. I have the rest of the code working with a static object but im new to handling json data and returning it from a function. Below is my working function and I need to return the data to a variable that is accessible by other function. Any Help Is Much appreciated

func latestMovieReleases()
    {
        URLSession.shared.dataTask(with: latestReleasesURL!) {(data, response, error) in
        do
            {
                let movies = try JSONDecoder().decode([latestReleasesJSON].self, from: data!)

                for movie in movies
                {
                    print(movie.title)
                }
            }
            catch
            {
                print("We Got An Error :- ")
                print(error)
            }
        }.resume()
    }

Here is the struct that is located in my structures file

struct latestReleasesJSON: Decodable
{
    let id: String
    let title: String
    let posterurl: String
    let year: String
    let releaseDate: String
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

0

You can try

func latestMovieReleases(completion:@escaping([latestReleasesJSON]? -> ()))
{
    URLSession.shared.dataTask(with: latestReleasesURL!) {(data, response, error) in

      guard let data = data else {completion(nil) ; return } 
      do
        {
            let movies = try JSONDecoder().decode([latestReleasesJSON].self, from: data)

            for movie in movies
            {
                print(movie.title)
            }

            completion(movies)
        }
        catch
        {
            print("We Got An Error :- ")
            print(error)
            completion(nil)
        }
    }.resume()
}

Call

 latestMovieReleases { (res) in
    if let re = res {
      print(re)
    }
 }

struct latestReleasesJSON: Decodable {
  let id,title,posterurl,year,releaseDate: String 
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87