当没有图像Swift 4时,应用程序崩溃

时间:2018-03-09 17:51:56

标签: swift uiimageview image-caching

我在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()
    }
}

0 个答案:

没有答案