首页 > 解决方案 > 为什么从 url 下载图像返回 nil?

问题描述

我正在尝试下载上传到我的数据库存储的图像,并且图像的链接在我的实时数据库中。链接没有问题,但是当我使用我的方法从链接返回图像时,我得到了零。我强制包装它,因为它现在需要返回一个图像。

这是我的代码:

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!
 }

请让我知道为什么我的代码失败了。

标签: swiftfirebaseuiimage

解决方案


您的代码的问题是 dataTask 方法是异步的。您将在下载过程完成之前返回结果。您需要在您的方法中添加一个完成处理程序,以便在完成后返回图像或错误:


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
    }
}

推荐阅读