URLCache(CS193P 作业 6)
URLCache (CS193P Assignment 6)
我现在在斯坦福 iOS Swift 作业 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() 中。我做错了吗?
非常感谢有用的建议!
您可以通过使用 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
}
}
我现在在斯坦福 iOS Swift 作业 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() 中。我做错了吗?
非常感谢有用的建议!
您可以通过使用 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
}
}