gpt4 book ai didi

ios - Alamofire 4 Swift 缓存控制 - HTTP 状态代码 304(如果修改自)

转载 作者:行者123 更新时间:2023-11-28 06:23:03 32 4
gpt4 key购买 nike

当我从服务器收到 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
}

有人有想法吗?有疑问是我自己写的。

最佳答案

如果状态代码是 304,我设法恢复了旧的缓存内容:

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)
}()

func getData(url:URLConvertible,completionHadler:@escaping(Data?,ErrorMessage?)->Void){

let headers: HTTPHeaders =
[ "Authorization":token!,
"Accept": "application/json",
"if-None-Match": self.loadEtagUserDefault(keyValue: "Etag")
]


self.sessionManager.request(url, method: .get, parameters:nil, headers: headers)

.validate()

.responseJSON { (response) in

switch (response.result) {
case .success:

// SAVE THE RESPONSE INSIDE THE CACHE

self.saveCache(response)

//---

if let unwrappedResponse = response.response {
_ = unwrappedResponse.statusCode
}
// If all went well, I'll return the date
       // Recovery Etag from the Header
let etag = response.response?.allHeaderFields["Etag"] as? String
//update in memoria Etag
self.saveEtagUserDefault(etagValue: etag!, key: "Etag")

print("stato codice: \(String(describing: response.response?.statusCode))")
completionHadler(response.data,nil)

break
case .failure(let error):
print(error.localizedDescription)
let statusCode = response.response?.statusCode
let url1:URLRequest? = try! response.request?.asURLRequest()

//Nel caso lo status code è nil perciò il sito non e raggiungibile restituisce la vecchia cache
guard let _ = statusCode else {

let dataOld = self.loadOldDataCache(url: url1!)
completionHadler(dataOld,nil)

return
}
// If the status code is 304 (no change) I return the old cache
if statusCode == 304 {

print("beccato codice 304 ***")
let dataOld = self.loadOldDataCache(url: url1!)
guard let _ = dataOld else {
completionHadler(nil,ErrorMessage.error(description: "data nil"))
return
}
completionHadler(dataOld,nil)
return
}


// *** IN CASE OF ERROR 401 refresh the token and recursively call the same method
print("error - > \n \(error.localizedDescription) \n")

print("stato codice2: \(String(describing: statusCode))")


}


}

}


//Save the response in the cache
private func saveCache(_ response: (DataResponse<Any>)) {
let cachedResponse = CachedURLResponse(response: response.response!, data: response.data!, userInfo: nil, storagePolicy: .allowed)
let mycache:URLCache = self.sessionManager.session.configuration.urlCache!
mycache.storeCachedResponse(cachedResponse, for: response.request!)
}


// Given a Request URL returns the old CACHE in case the site is unresponsive or offline
private func loadOldDataCache(url:URLRequest)->Data?{
let myCache:URLCache = self.sessionManager.session.configuration.urlCache!
let cacheResponse = myCache.cachedResponse(for: url)
return cacheResponse?.data
}

// Except in memory Etag
private func saveEtagUserDefault(etagValue:String,key:String)->Void{

UserDefaults.standard.set(etagValue, forKey:key)
UserDefaults.standard.synchronize()

}
// Recovery from the memory Etag
private func loadEtagUserDefault(keyValue:String)->String{
return UserDefaults.standard.object(forKey: keyValue) as? String ?? "0"
}

}

关于ios - Alamofire 4 Swift 缓存控制 - HTTP 状态代码 304(如果修改自),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42788773/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com