iosswiftjsondecoder

Sending string from JSON data to variable outside of the function


I am attempting to take a string from JSON data and set it to a variable. My problem is that the variable shows as empty. I am using JSONDecoder to retrieve the JSON data and setting the string to a variable outside of the function. I then want to use that variable inside of another function

When I print the variable it still shows up as blank even after the function has loaded. Within the function the string appears correctly.

Code:

var filmTitle = ""

override func viewDidLoad() {
    super.viewDidLoad()


loadFilms()
print(self.filmTitle) //Prints as an empty string

}

func loadFilms() {
    
    let id = filmId
    let apiKey = "97a0d64910120cbeae9df9cb675ad235"
    let url = URL(string: "https://api.themoviedb.org/3/movie/\(id)?api_key=\(apiKey)&language=en-US")
    let request = URLRequest(
        url: url! as URL,
        cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData,
        timeoutInterval: 10 )
    
    let session = URLSession (
        configuration: URLSessionConfiguration.default,
        delegate: nil,
        delegateQueue: OperationQueue.main
    )
    
    let task = session.dataTask(with: request, completionHandler: { (dataOrNil, response, error) in
        if let data = dataOrNil {
            do { let details = try! JSONDecoder().decode(Details.self, from: data)
        self.filmTitle = details.title
        print(self.filmTitle) //string prints correctly

                        }
                    }
                })
    
    
    task.resume()
    
}

What am I missing to correctly set the string to the variable?


Solution

  • The solution to this problem was to reload the collection view that the array was being sent to within the decoder function after the data was set to the array.