gpt4 book ai didi

ios - NSURLSession 不缓存请求

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

我希望缓存我的 api 响应 json,以便用户可以继续在离线模式下使用该应用程序。但是,结果没有被缓存,并且当我关闭 WiFi 时会显示错误警报。

 let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
guard (data != nil) else {
self.showConnectionErrorAlert()
return
}
}

task.resume()

这就是我配置 NSURLCache 的方式:

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

let cacheSizeMemory = 500*1024*1024; // 500 MB
let cacheSizeDisk = 500*1024*1024; // 500 MB
let sharedCache = NSURLCache.init(memoryCapacity: cacheSizeMemory, diskCapacity: cacheSizeDisk, diskPath: "nsurlcache")
NSURLCache.setSharedURLCache(sharedCache)
sleep(1);


return true
}

这是在线时的响应 header :

Optional( { URL: http://api.nytimes.com/svc/search/v2/articlesearch.json?&page=2&fq=document_type:(article)&sort=newest&api-key=32a4d3342b658b316d4b1369d04a6e5b:16:73440927 } { status code: 200, headers { "Access-Control-Allow-Credentials" = true; "Access-Control-Allow-Origin" = "*"; "Content-Length" = 20212; "Content-Type" = "application/json; charset=UTF-8"; Date = "Fri, 13 Nov 2015 20:02:49 GMT"; Server = "nginx/1.4.1"; Vary = "Accept-Encoding"; "X-Cached" = MISS; "X-Mashery-Responder" = "prod-j-worker-atl-04.mashery.com"; "X-Powered-By" = "PHP/5.3.27"; } })

离线时出现错误:

Optional(Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={NSErrorFailingURLStringKey=http://api.nytimes.com/svc/search/v2/articlesearch.json?&page=1&fq=document_type:(article)&sort=newest&api-key=32a4d3342b658b316d4b1369d04a6e5b:16:73440927, _kCFStreamErrorCodeKey=8, NSErrorFailingURLKey=http://api.nytimes.com/svc/search/v2/articlesearch.json?&page=1&fq=document_type:(article)&sort=newest&api-key=32a4d3342b658b316d4b1369d04a6e5b:16:73440927, NSLocalizedDescription=The Internet connection appears to be offline., _kCFStreamErrorDomainKey=12, NSUnderlyingError=0x7bfd1360 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8}}})

最佳答案

服务器响应不包含任何缓存 header ,因此不会缓存任何内容。

如果要添加到缓存中,则需要更改服务器发送的响应 header 或手动将响应添加到缓存中。执行此操作后,您可以在请求上设置 cachePolicy 以指示应如何以及何时使用缓存(因为缓存可能已过时)。

let newCachedResponse = NSCachedURLResponse(response:response, data:response.data, userInfo:nil, storagePolicy:XXX)
NSURLCache.sharedURLCache().storeCachedResponse(newCachedResponse, forRequest:request)

关于ios - NSURLSession 不缓存请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33700746/

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