Swift 等效于使用 URLSession 的 @HotJard 解决方案
extension CachedURLResponse {
func response(withExpirationDuration duration: Int) -> CachedURLResponse {
var cachedResponse = self
if let httpResponse = cachedResponse.response as? HTTPURLResponse, var headers = httpResponse.allHeaderFields as? [String : String], let url = httpResponse.url{
headers["Cache-Control"] = "max-age=\(duration)"
headers.removeValue(forKey: "Expires")
headers.removeValue(forKey: "s-maxage")
if let newResponse = HTTPURLResponse(url: url, statusCode: httpResponse.statusCode, httpVersion: "HTTP/1.1", headerFields: headers) {
cachedResponse = CachedURLResponse(response: newResponse, data: cachedResponse.data, userInfo: headers, storagePolicy: cachedResponse.storagePolicy)
}
}
return cachedResponse
}
}
然后在您的自定义类中实现 URLSessionDataDelegate 协议
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
if dataTask.currentRequest?.cachePolicy == .useProtocolCachePolicy {
let newResponse = proposedResponse.response(withExpirationDuration: 60)
completionHandler(newResponse)
}else {
completionHandler(proposedResponse)
}
}
不要忘记创建您的配置和会话,将您的自定义类作为委托参考传递,例如
let session = URLSession(
configuration: URLSession.shared.configuration,
delegate: *delegateReference*,
delegateQueue: URLSession.shared.delegateQueue
)
let task = session.dataTask(with: request)
task.resume()