从 json url 下载图像不起作用

问题描述

我正在尝试从 json Api 获取一些数据并将这些数据与图像一起显示。首先,我有一个从 Api 获取数据的函数,然后我有一个下载图像数据的函数。问题是第二个函数似乎无法正常工作,并且从未收到图像数据。

func fetchAPI() {

        URLSession.shared.dataTask(with: url) { (data,response,error) in

    /* Code that decodes the json and gets the imageURL string */

                dispatchQueue.main.async {

                    self.downloadImage(url: imageURL) // call the function that downloads the imageData
                }
            } catch {
                print("Error: \(error.localizedDescription)")
            }
        }
        .resume()
    } 

下载图片函数

func downloadImage(url: String) {

        guard let imageURL = URL(string: url) else {
            print("Error: Invalid image URL")
            return
        }
        URLSession.shared.dataTask(with: imageURL) { data,error in
            guard let recievedData = data,error == nil  else {
                print("Error: No Data")
                return
            }
                        print("Got Data") // Doesn't output to console
                        print(recievedData) // Doesn't output to console
            dispatchQueue.main.async {
                self.imageData = recievedData <- nothing
            }
        }
    }

解决方法

调用.resume()

func downloadImage(url: String) {

        guard let imageURL = URL(string: url) else {
            print("Error: Invalid image URL")
            return
        }
        URLSession.shared.dataTask(with: imageURL) { data,response,error in
            guard let recievedData = data,error == nil  else {
                print("Error: No Data")
                return
            }
                        print("Got Data") // Doesn't output to console
                        print(recievedData) // Doesn't output to console
            DispatchQueue.main.async {
                self.imageData = recievedData <- Nothing
            }
        }
        .resume()
    }