我尝试从网址缓存图片,以使我的表格滚动得更顺畅。这似乎并没有缓解他们,我无法弄清楚我做错了什么。谁能告诉我这有什么问题?
let imageCache = NSCache()
extension UIImageView {
func loadImageUsingCacheWithUrlString(urlString: String) {
self.image = nil
//check cache for image first
if let cachedImage = imageCache.objectForKey(urlString) as? UIImage {
self.image = cachedImage
return
}
//otherwise fire off a new download
let url = NSURL(string: urlString)
NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) in
//download hit an error so lets return out
if error != nil {
print(error)
return
}
dispatch_async(dispatch_get_main_queue(), {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: urlString)
self.image = downloadedImage
}
})
}).resume()
}
}
我觉得应该有一个其他{在开始新的下载之前,但即使我尝试过,我也不认为它正常工作。我甚至尝试以这种方式运行它,滚动表格以确保它有机会缓存所有图像,然后删除整个下载部分,这样它只会加载缓存的图像,并且没有图像出现所以我不会#39 ;认为它实际上是在缓存它们。
答案 0 :(得分:0)
很抱歉,如果这是一个糟糕的问题。这是最终奏效的:
var imageCache = NSMutableDictionary()
extension UIImageView {
func loadImageUsingCacheWithUrlString(urlString: String) {
self.image = nil
if let img = imageCache.valueForKey(urlString) as? UIImage{
self.image = img
}
else{
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(NSURL(string: urlString)!, completionHandler: { (data, response, error) -> Void in
if(error == nil){
if let img = UIImage(data: data!) {
imageCache.setValue(img, forKey: urlString) // Image saved for cache
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = img
})
}
}
})
task.resume()
}
}
}
我想我有些不合时宜的东西。