gpt4 book ai didi

swift - 当滚动甚至存储在 NSCache 中时,UIImage 一直保持加载 - swift

转载 作者:搜寻专家 更新时间:2023-11-01 06:27:46 26 4
gpt4 key购买 nike

我是 iOS 编程新手。我正在创建一个简单的应用程序,它从特定链接 ( firestore ) 加载图像。图像完全从服务器下载,并像往常一样在 collectionview 的每个单元格中可见。但问题是,当我向上或向下滚动时,这些图像会再次加载。我认为它再次开始下载,因为当我关闭互联网连接时,这些图像不再被加载。

这是我如何在每个单元格中设置图像

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CollectionCell

let explore = dataAppend[indexPath.item]
//cell.imageDisplay.text = explore.title
if let imageUrl = explore.image {
cell.imageDisplay.loadImageWithData(urlString: imageUrl)
}
//print(explore.image)
return cell
}

这是加载图像的样子 loadImageWithData(urlString: imageUrl)

let imageCache = NSCache<NSString, UIImage>()

class CustomImageView : UIImageView {

var imageUrlString: String?

func loadImageWithData (urlString: String) {

imageUrlString = urlString
if let imageFromCache = imageCache.object(forKey: urlString as NSString){
self.image = imageFromCache
}
image = nil
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

if let err = error {
print(err.localizedDescription)
}
if let data = data {

DispatchQueue.main.async {
let imageToCache = UIImage(data: data)
if self.imageUrlString == urlString {
self.image = imageToCache
}
imageCache.setObject(imageToCache!, forKey: urlString as NSString)
}
}
}).resume()
}
}

最佳答案

 var imageCache = NSMutableDictionary()

class CustomImageView: UIImageView {

func loadImageUsingCacheWithUrlString(urlString: String) {

self.image = nil

if let img = imageCache.valueForKey(urlString) as? UIImage{
self.image = img
return
}
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
DispatchQuee.main.asyn{
self.image = img

}


}
})
task.resume()
}
}

关于swift - 当滚动甚至存储在 NSCache 中时,UIImage 一直保持加载 - swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51645280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com