【问题标题】:Downloading Image from json url doesn't work从 json url 下载图像不起作用
【发布时间】:2021-02-08 10:32:51
【问题描述】:

我正在尝试从 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, 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() 未在 downloadImage(url:) 中调用。所以 url 任务没有启动。
  • 谢谢。但是我在这里所做的被认为是好的做法吗?或者有更好的方法吗?我正在使用(SwiftUI)

标签: json swift swiftui urlsession


【解决方案1】:

调用 .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()
    }

【讨论】:

  • 谢谢。但是我在这里所做的被认为是好的做法吗?或者有更好的方法吗?我正在使用(SwiftUI)
猜你喜欢
  • 2017-08-13
  • 2018-08-03
  • 2018-01-09
  • 1970-01-01
  • 2019-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
相关资源
最近更新 更多