我现在在斯坦福iOS Swift Assignment 6上,其中一项所需任务是使用URLCache缓存本地磁盘上的映像。经过几天的谷歌搜索,我仍然无法弄清楚如何使用它。如果有人能指点我一个好导游,那会很有帮助!
在尝试理解官方文档后,我的代码就像这样。官方文档没有我可以参考的示例代码,这没有任何帮助:(
let urlCache = URLCache.shared
所需的任务是设置缓存并指定大小限制。我尝试初始化URLCache并传递参数中的大小。它工作,但存储和获取缓存似乎不起作用。如果每次启动应用程序(或视图控制器)时初始化URLCache,是否会忽略先前创建和存储的缓存?
我认为此代码没有问题?从缓存中读取数据
if let cachedURLResponse = urlCache.cachedResponse(for: URLRequest(url: url)) {
if let fetchedImage = UIImage(data: cachedURLResponse.data) {
image = fetchedImage
}
}
我把数据写入缓存
urlCache.storeCachedResponse(CachedURLResponse(response: URLResponse(), data: imageData), for: URLRequest(url: url))
如何正确初始化URLResponse?我查看了init方法,它还要求将url作为参数传入。发现这很奇怪,因为url也在URLRequest()中。我做错了吗?
非常感谢有用的建议!
答案 0 :(得分:1)
您可以通过使用URLSession请求图像数据然后使用其完成处理程序中提供的数据和响应来使用URLCache,例如:
import UIKit
class GalleryCollectionViewController: UICollectionViewController, UICollectionViewDragDelegate, UICollectionViewDropDelegate, UICollectionViewDelegateFlowLayout {
// MARK: - Model
var gallery: Gallery?
// MARK: - Properties
private var cache = URLCache.shared
private var session = URLSession(configuration: .default)
override func viewDidLoad() {
super.viewDidLoad()
cache = URLCache(memoryCapacity: 100, diskCapacity: 100, diskPath: nil) // replace capacities with your own values
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GalleryCell", for: indexPath)
if let galleryCell = cell as? GalleryCollectionViewCell {
galleryCell.image = nil
galleryCell.imageView.isHidden = true
if let url = gallery?.images[indexPath.item].url {
let request = URLRequest(url: url.imageURL) // imageURL from Utilities.swift of Stanford iOS course
if let cachedResponse = cache.cachedResponse(for: request), let image = UIImage(data: cachedResponse.data) {
galleryCell.image = image
galleryCell.imageView.isHidden = false
} else {
DispatchQueue.global(qos: .userInitiated).async { [weak self, weak galleryCell] in
let task = self?.session.dataTask(with: request) { (urlData, urlResponse, urlError) in
DispatchQueue.main.async {
if urlError != nil { print("Data request failed with error \(urlError!)") }
if let data = urlData, let image = UIImage(data: data) {
if let response = urlResponse {
self?.cache.storeCachedResponse(CachedURLResponse(response: response, data: data), for: request)
}
galleryCell?.image = image
} else {
galleryCell?.image = UIImage(named: "placeholder")
}
galleryCell?.imageView.isHidden = false
}
}
task?.resume()
}
}
}
}
return cell
}
}