gpt4 book ai didi

ios - 设置缓存时间 AFNetworking swift 2

转载 作者:行者123 更新时间:2023-11-28 06:53:29 33 4
gpt4 key购买 nike

我正在使用代码 AFNetworking 加载数据

let manager = AFHTTPRequestOperationManager()
manager.requestSerializer.cachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad
manager.responseSerializer = AFHTTPResponseSerializer()

let testUrl = "https://www.google.com/maps/vt/pb=!1m8!3m7!1m2!1u2816!2u5888!2m2!1u1536!2u512!3i6!2m3!1e0!2sm!3i333!2m20!1e2!2spsm!4m2!1sgid!2sWejnA6yw2AIgHrbvnAUOAg!4m2!1ssp!2s1!8m11!13m9!2sa!15b1!18m5!2b1!3b0!4b1!5b0!6b0!19b1!19u12!3m2!2sen!5e1105!4e4!11m2!1e2!2b1&authuser=0"

manager.GET(testUrl,
parameters: nil,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
print("afnetworking GET success1")
},
failure: { (operation: AFHTTPRequestOperation?,error: NSError!) in
print("afnetworking GET 1 - Error: " + error.localizedDescription)
})

当数据在缓存中时,它会从缓存中给我数据...没问题,
但我怎么能
1)- 设置缓存策略,只缓存1小时
2)- 当服务器没有缓存 header 时它不缓存,对于这种情况也将数据缓存一个小时。

最佳答案

对于来自 Swift 宗教的人,我编写了 AFHTTPSessionManager 扩展,其中包含从 AFNetworking 3.0< 调用 self.setDataTaskWillCacheResponseBlock: 的方法 并修改 Cache-Control 响应 header value :

extension AFHTTPSessionManager {
//duration in seconds
func forceCacheResponse(duration:Int) {
self.setDataTaskWillCacheResponseBlock({
(session:NSURLSession, task:NSURLSessionDataTask, proposedResponse:NSCachedURLResponse) -> (NSCachedURLResponse) in
if let response = proposedResponse.response as? NSHTTPURLResponse {
var headers = response.allHeaderFields as! [String:String]
headers["Cache-Control"] = String(format: "max-age=%@", arguments: [duration])

let modifiedResponse = NSHTTPURLResponse(URL: response.URL!, statusCode: response.statusCode, HTTPVersion: "1.1", headerFields: headers)
if (modifiedResponse != nil) {
let cachedResponse = NSCachedURLResponse(response: modifiedResponse!, data: proposedResponse.data, userInfo: proposedResponse.userInfo, storagePolicy: NSURLCacheStoragePolicy.Allowed)
return cachedResponse
}
}

return proposedResponse
})
}
}

现在你的用法非常简单:

let manager = AFHTTPSessionManager()
manager.forceCacheResponse(604800)

关于ios - 设置缓存时间 AFNetworking swift 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34312142/

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