我创建了一个函数,该函数将从 url 获取图像并将其分配给一个变量,然后它将该变量作为图像返回。虽然它没有返回任何东西并且崩溃了。
func downloadImage(imageUrl:String) -> UIImage {
var imageDownloaded : UIImage?
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let task = session.dataTask(with: URL(string: imageUrl)!) { (data, response, error) in
if error != nil {
return
}
do {
imageDownloaded = try UIImage(data: data!)
} catch {
print("Fail")
}
}
task.resume()
return imageDownloaded! //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
}
最佳答案
您正试图在变量“imageDownloaded”没有任何值(即 nil)时强行展开它。这是因为下载图像数据需要时间。
要解决这个问题,您应该使用完成处理程序
func downloadImage(imageUrl:String, @escaping completionHandler: (UIImage?)->()) {
var imageDownloaded : UIImage?
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let task = session.dataTask(with: URL(string: imageUrl)!) { (data, response, error) in
if error != nil {
return
}
do {
imageDownloaded = try UIImage(data: data!)
completionHandler(imageDownloaded!)
} catch {
print("Fail")
completionHandler(nil)
}
}
task.resume()
}
关于ios - 尝试使用 URLsession 从 DataTask 创建图像无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58903141/