我在swift 4
制作的应用在新闻提供商没有图片时崩溃了!因此,当我滚动一篇没有图像的文章时,它会崩溃,我收到错误:
线程1:致命错误:在解包可选值时意外发现nil
以下是我的图片代码:
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func downloadImage(from url: String){
let urlRequest = URLRequest(url: URL(string: url)!)
image = nil
if let imageFromCache = imageCache.object(forKey: url as AnyObject) as? UIImage {
self.image = imageFromCache
return
}
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async {
let imageToCache = UIImage(data: data!)
imageCache.setObject(imageToCache!, forKey: url as AnyObject)
self.image = imageToCache
}
}
task.resume()
}
}