为什么从 url returns 下载图像为零?

why downloading image from url returns nil?

我正在尝试下载已上传到我的数据库存储的图像,图像的 link 在我的实时数据库中。 link 没有问题,但是当我使用我的方法 return 来自 link 的图像时,我得到的结果为零。我强制包装它,因为它现在需要 return 图片。

这是我的代码:

func getImageFromUrl(url: URL) -> UIImage {
    var tempImage: UIImage? = nil

    print("INSIDE URL -> \(url.absoluteString)")

    URLSession.shared.dataTask(with: url) { (data, response, error) in
       if error != nil {
           print("Error on getImageFromUrl : \(error!.localizedDescription)")
           return
       }

       print("Image data " + data.debugDescription)

       DispatchQueue.main.async {
           tempImage = UIImage(data: data!)!
           print("TEMP IMAGE > \(String(describing: tempImage?.images![0]))")
       }
    }.resume()

    if tempImage == nil {
        print("IMAGE IS NIL!")
    }
    return tempImage!
 }

请告诉我为什么我的代码失败了。

您的代码存在的问题是 dataTask 方法是异步的。在下载过程完成之前,您正在 return 查看结果。你需要的是在你的方法中添加一个完成处理程序到 return 图像或完成后的错误:


import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

func getImage(from url: URL, completion: @escaping (UIImage?, Error?) -> ()) {
    print("download started:", url.absoluteString)
    URLSession.shared.dataTask(with: url) { data, reponse, error in
        guard let data = data else {
            completion(nil, error)
            return
        }
        print("download finished:")
        completion(UIImage(data: data), nil)
    }.resume()
}

let url = URL(string: "https://i.stack.imgur.com/varL9.jpg")!
getImage(from: url) { image, error in
    guard let image = image else {
        print("error:", error ?? "")
        return
    }
    print("image size:", image.size)
    // use your image here and don't forget to always update the UI from the main thread
    DispatchQueue.main.async {
        self.imageView.image = image
    }
}