图片缓存 swift 3
ImageCache swift 3
您好,我想缓存来自 json 的图像。我创建了一个网络服务,它下载并解析 json,我使用 func downloadImage() 发出 imageurl.Then 的 http 请求,我用这个 func 更新了我的剧集,但图像仍在滚动下载
var episode: Product! {
didSet {
self.updateUI()
}
}
let imageCache = NSCache<AnyObject, AnyObject>()
func updateUI()
{
menuItemNameLabel?.text = episode.title
ingredientsItemLabel?.text = episode.summary
priceItemLabel?.text = episode.price
menuItemImageView?.image = UIImage(named: "Koulourades")
if let thumbnailURL = episode.thumbnailURL {
let networkService = NetworkService(url: thumbnailURL)
networkService.downloadImage({ (imageData) in
if let imageFromCache = self.imageCache.object(forKey: self.episode.thumbnailURL as AnyObject) as? UIImage {
DispatchQueue.main.async(execute: {
self.menuItemImageView?.image = imageFromCache
return
})
}
DispatchQueue.main.async(execute: {
let imageToCache = UIImage(data: imageData as Data)
self.imageCache.setObject(imageToCache!, forKey: self.episode.thumbnailURL as AnyObject)
self.menuItemImageView?.image = imageToCache
})
})
}
}//--end updateUI()
您需要解决问题的方法称为延迟加载,应用程序将立即下载图像并将其缓存到内存中。
有多个第三方库可用于缓存图像。
像 ,
这样的图书馆
1) HanekeSwift -> https://github.com/Haneke/HanekeSwift
2) 翠鸟 -> https://github.com/onevcat/Kingfisher
3) SDWebImage -> https://github.com/rs/SDWebImage
4) AlamofireImage -> https://github.com/Alamofire/AlamofireImage
您好,我想缓存来自 json 的图像。我创建了一个网络服务,它下载并解析 json,我使用 func downloadImage() 发出 imageurl.Then 的 http 请求,我用这个 func 更新了我的剧集,但图像仍在滚动下载
var episode: Product! {
didSet {
self.updateUI()
}
}
let imageCache = NSCache<AnyObject, AnyObject>()
func updateUI()
{
menuItemNameLabel?.text = episode.title
ingredientsItemLabel?.text = episode.summary
priceItemLabel?.text = episode.price
menuItemImageView?.image = UIImage(named: "Koulourades")
if let thumbnailURL = episode.thumbnailURL {
let networkService = NetworkService(url: thumbnailURL)
networkService.downloadImage({ (imageData) in
if let imageFromCache = self.imageCache.object(forKey: self.episode.thumbnailURL as AnyObject) as? UIImage {
DispatchQueue.main.async(execute: {
self.menuItemImageView?.image = imageFromCache
return
})
}
DispatchQueue.main.async(execute: {
let imageToCache = UIImage(data: imageData as Data)
self.imageCache.setObject(imageToCache!, forKey: self.episode.thumbnailURL as AnyObject)
self.menuItemImageView?.image = imageToCache
})
})
}
}//--end updateUI()
您需要解决问题的方法称为延迟加载,应用程序将立即下载图像并将其缓存到内存中。
有多个第三方库可用于缓存图像。
像 ,
这样的图书馆1) HanekeSwift -> https://github.com/Haneke/HanekeSwift
2) 翠鸟 -> https://github.com/onevcat/Kingfisher
3) SDWebImage -> https://github.com/rs/SDWebImage
4) AlamofireImage -> https://github.com/Alamofire/AlamofireImage