当我从服务器收到HTTP状态代码304时,服务器不会发送任何内容数据,因为没有任何更改。
现在我想使用Alamofire 4(适用于Swift 3)的缓存控件。但我无法弄清楚它是如何运作的。我找到了Alamofire 3 here
的一些例子 Alamofire.request(req)
.response {(request, res, data, error) in
let cachedURLResponse = NSCachedURLResponse(response: res!, data: (data as NSData), userInfo: nil, storagePolicy: .Allowed)
NSURLCache.sharedURLCache().storeCachedResponse(cachedURLResponse, forRequest: request)
}
所以我认为Alamofire 4中的结构类似。但我的内容保存在哪里?我希望我可以做这样的事情
伪代码:
if response.statusCode == 304 {
return cacheControl.response
}
有人有想法吗? 有疑问,我自己写了。
答案 0 :(得分:1)
我设法恢复旧缓存内容,以防状态代码为304,如下所示:
$form_data = array(
'sr_no' => $no_rows,
'name' => $name,
'devicemode' => $devicemode,
'rating' => $rating,
'comment' => $comment,
//'timing' => $diff
);
if($no_rows == 0)
{
fputcsv($file_open, array_keys($form_data));
}
和
let sessionManager: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.requestCachePolicy = .reloadIgnoringCacheData
configuration.timeoutIntervalForRequest = 60
let memoryCapacity = 500 * 1024 * 1024; // 500 MB
let diskCapacity = 500 * 1024 * 1024; // 500 MB
let cache = URLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "shared_cache")
configuration.urlCache = cache
return SessionManager(configuration: configuration)
}()
答案 1 :(得分:0)
我所做的是我为Alamofire创建了自己的NetworkManager。
class NetworkManager {
static let sharedInstance: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
configuration.timeoutIntervalForRequest = 20.0
configuration.timeoutIntervalForResource = 20.0
configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
configuration.urlCache = nil
return SessionManager(configuration: configuration)
}()
}
重要的一行是configuration.urlCache = nil
。所以Alamofire不会缓存任何东西。当然我知道这不是正确的方法,但对于我的用例来说,这是一个o-kay的解决方案。
你这样称呼这个经理
NetworkManager.sharedInstance.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: contentAuthorization).responseJSON { (response) in
switch(response.result) {
case .success(_):
//success
case .failure(let errorValue):
print(errorValue)
}
}