iosswiftnsurlsessiondownloadtaskuiscenedelegate

How can I call a function from scene delegate which downloads an URL in a view controller?


I am downloading an image in my view controller. I want to update my image every time the app enters the foreground. I tried to call the function to download the image from the scene delegate, but unfortunately, I get the error "Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value", when I try that.

This is my code to download the image which works fine except when I call it from the scene delegate.

        let urlSession = URLSession(configuration: .default)

        let url = URL(string: "https://jarisstoriesphotographyphoto.files.wordpress.com/2020/06/menu1.png")!

        // Create Data Task

        let dataTask = urlSession.dataTask(with: url) { [weak self] (data, _, error) in
            if let error = error {
                print(error)
            }
            if let data = data {
                DispatchQueue.main.async {
                    // Create Image and Update Image View
                    // self?.imageView.image
                    self?.imageView.image = UIImage(data: data)
                }
            }
        }
        // Start Data Task
        dataTask.resume()

This is the code I used in my scene delegate. I also tried to call the download function in the "willConnectTo" but that gave me the same error.

let viewController = ViewController()

func sceneWillEnterForeground(_ scene: UIScene) {
     viewController.downloadImage()
}

Help is very appreciated.


Solution

  • If you want to start a download task every time the app enters foreground, within a view controller then you should do the task in viewWillAppear of the view controller. Here's an example:

    class ViewController: UIViewController {
        // ...
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            let urlSession = URLSession(configuration: .default)
             let url = URL(string: "https://jarisstoriesphotographyphoto.files.wordpress.com/2020/06/menu1.png")!
    
             // Create Data Task
    
             let dataTask = urlSession.dataTask(with: url) { [weak self] (data, _, error) in
                 if let error = error {
                     print(error)
                 }
                 if let data = data {
                     DispatchQueue.main.async {
                         // Create Image and Update Image View
                         // self?.imageView.image
                         self?.imageView.image = UIImage(data: data)
                     }
                 }
             }
             // Start Data Task
             dataTask.resume()
        }
    }