NSURLCache 和 ETags

问题描述 投票:0回答:2

NSURLCache
是否透明地处理服务器收到的ETag?

我的意思是:它是否会自动为每个 URL 请求存储 ETag,然后在提交对同一 URL 的请求时发送相应的

If-None-Match
? 还是我必须自己管理?

ios etag nsurlcache
2个回答
22
投票

是的,如果您设置其缓存模式,它确实会透明地处理它:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                                           cachePolicy: NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60];

注意:您根本看不到请求中的标头,如果服务器返回 304 响应,您将只能看到从缓存透明加载的 200 响应。


0
投票

对于后代,这是如何将 ETag 与 swift 结合使用:

let API_HEADER_FIELD_NONE_MATCH = "If-None-Match"
let API_HEADER_FIELD_ETAG = "Etag"
let API_REQUEST_SUCCESS : Int = 200
let API_REQUEST_NOT_MODIFIED : Int = 304

//inject ETag
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [API_HEADER_FIELD_NONE_MATCH: storedEtag]
config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
let urlSession = URLSession(configuration: config)
        
let (jsonData, response) = try await urlSession.data(from: dataURL)
        
guard let httpResponse = response as? HTTPURLResponse else {
      throw some error
}
        
switch httpResponse.statusCode {
case API_REQUEST_SUCCESS:
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .iso8601
    
    if let responseETag = httpResponse.allHeaderFields[API_HEADER_FIELD_ETAG] as? String {
        let decodedData = try decoder.decode(TrackerData.self, from: jsonData)
        return (decodedData, responseETag)
    } else {
        throw some error "Missing ETag"
    }
case API_REQUEST_NOT_MODIFIED:
    //the data represented by the stored etag is up to date
default:
    throw APIError.apiError(reason: "Unexpected HTTP response code \(httpResponse.statusCode)")
}
© www.soinside.com 2019 - 2024. All rights reserved.