0

I am making a global function to hit the api and get response from the server. then that value is returned in the form of array of class but its returning nil when printing outside the data task the value is printed inside the data task

here is my code for the global function

    func fetchMovieList(url: String ) -> [movies]{
            var movie = [movies]()
            global.currentUrl = url
            // constant to store the url for nowShowing
            let convertdUrl = URL(string: url)

            // creating a Url session for fetching json from the server
            URLSession.shared.dataTask(with: convertdUrl!){(data, response, error) in


                // if request is error free then decode the json using json decoder and assigning the values to the array
                guard let data = data else {return}
                do{
                    movie = try JSONDecoder().decode([movies].self, from: data)
                    //movieList.comingSoon = movieList.nowShowing
                    print("\(movie)")

                }catch {
                    print("Error")
                }
                }.resume()
            print("\(movie)")
            return movie
}
Rishabh.t
  • 13
  • 1
  • 8

1 Answers1

0
print("\(movie)")

This is returning nil because that line get executed before you have received any data from server. so movie will not be containing any data at that time. and once you get response from server, you store data in movie and then print it.

If you are facing issue returning data from this function you can use the code given in the below link. Here

MRizwan33
  • 2,723
  • 6
  • 31
  • 42
Krishna Maru
  • 164
  • 13