我创建了一个函数,该函数将从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
}
答案 0 :(得分:1)
您试图在变量'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()
}