我有UITableView
列出了其中包含图片的社交媒体帖子。一旦所有帖子详细信息都已加载并且缓存的图像看起来不错,但是在加载时经常显示具有错误帖子的错误图像。
我一直在努力并回到这个问题上几个月了。我不认为这是一个加载问题,它几乎就像iOS将图像转储到任何旧单元格之前,直到找到正确的单元格为止,但是老实说我没有主意。
这是我的图像扩展名,它也负责缓存:
let imageCache = NSCache<NSString, AnyObject>()
extension UIImageView {
func loadImageUsingCacheWithUrlString(_ urlString: String) {
self.image = UIImage(named: "loading")
if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage {
self.image = cachedImage
return
}
//No cache, so create new one and set image
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if let error = error {
print(error)
return
}
DispatchQueue.main.async(execute: {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: urlString as NSString)
self.image = downloadedImage
}
})
}).resume()
}
}
这是我的UITableView
的简化版本:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let postImageIndex = postArray [indexPath.row]
let postImageURL = postImageIndex.postImageURL
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedItem", for: indexPath) as! FeedItem
cell.delegate = self
cell.postHeroImage.loadImageUsingCacheWithUrlString(postImageURL)
cell.postTitle.text = postArray [indexPath.row].postTitle
cell.postDescription.text = postArray [indexPath.row].postBody
return cell
}
FeedItem类包括prepareForReuse(),看起来像这样:
override func prepareForReuse() {
super.prepareForReuse()
self.delegate = nil
self.postHeroImage.image = UIImage(named: "loading")
}
我建议您使用SDWebImage
框架github link并使用此代码添加图像]
postHeroImage.sd_setImage(with: URL(string: "the image url"), placeholderImage: UIImage(named: "add a static image here which will visible until url image found"))
我希望这会工作..:)