swift - 为什么从 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!
}
请让我知道为什么我的代码失败了。
解决方案
您的代码的问题是 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
}
}
推荐阅读
- azure - 非分区流分析作业输出
- tinymce - 从插入日期时间拆分按钮中删除菜单
- r - 矢量化以提取和绑定非常嵌套的数据
- angular - 将 Angular 应用程序托管到 AWS S3 无法在 IOS 上运行
- sql - SQL 忽略一个具有 DISTINCT 但 ORDER BY 的字段
- javascript - 为什么我在 React JS 中遇到意外错误
- css - iPhone 12 Pro 的媒体查询在电脑上看起来很完美,但在手机上看起来完全不同
- button - 如何完全删除 SKIP 按钮?
- autogen - GNU Autogen IF
- html - 如何将新项目插入顶行的网格中?