问题描述
我有一个垂直滚动的 uicollectionview
,它使用子类 uiimageview
加载单元格,该子类通过 url 字符串下载图像。
我的网络调用在后台线程中,而且我正在使用缓存,但我不明白为什么滚动时仍然存在初始延迟。任何指导将不胜感激。
class ViewController: UIViewController {
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,for: indexPath as IndexPath) as! ACollectionViewCell
cell.populate(with: url)
return cell
}
}
class ACollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: PictureImageView!
func populate(with url: String) {
imageView.loadImageUsingUrlString(urlString: url)
}
}
let imageCache = NSCache<Nsstring,UIImage>()
class PictureImageView: UIImageView {
var imageUrlString: String?
func loadImageUsingUrlString(urlString: String) {
imageUrlString = urlString
image = #imageLiteral(resourceName: "blank_oval")
contentMode = .scaleAspectFill
layer.cornerRadius = frame.width/2
layer.masksToBounds = true
guard let url = URL(string: urlString) else {
image = #imageLiteral(resourceName: "blank_oval")
return
}
if let imageFromCache = imageCache.object(forKey: urlString as Nsstring) {
print("Fetched image from cache")
image = imageFromCache
return
}
URLSession.shared.dataTask(with: url) { data,response,error in
guard error == nil else {
print("Failed to fetch profile image:",error)
self.image = #imageLiteral(resourceName: "blank_oval")
return
}
dispatchQueue.main.async {
guard let data = data,let imagetoCache = UIImage(data: data) else {
self.image = #imageLiteral(resourceName: "blank_oval")
return
}
if self.imageUrlString == urlString {
dispatchQueue.main.async {
self.image = imagetoCache
}
}
imageCache.setobject(imagetoCache,forKey: urlString as Nsstring)
}
}.resume()
}
}
解决方法
在过去的 5 年里,我参与的几乎每个项目都使用它。这是远程服务所需图像的防弹实现。