我想让我的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
}
以下是在线时的回复标题:
可选({URL: http://api.nytimes.com/svc/search/v2/articlesearch.json?&page=2&fq=document_type:(article)&sort=newest&api-key=32a4d3342b658b316d4b1369d04a6e5b:16:73440927 } {状态代码:200,headers { “Access-Control-Allow-Credentials”= true; “Access-Control-Allow-Origin”=“*”; “Content-Length”= 20212; “Content-Type”=“application / json; charset = UTF-8”; 日期=“星期五,2015年11月13日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”; }})
离线时出现错误:
可选(错误域= NSURLErrorDomain代码= -1009“Internet 连接似乎处于脱机状态。“ 的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 = Internet连接似乎处于脱机状态。 _kCFStreamErrorDomainKey = 12,NSUnderlyingError = 0x7bfd1360 {错误域= kCFErrorDomainCFNetwork代码= -1009“(null)” UserInfo = {_ kCFStreamErrorDomainKey = 12,_kCFStreamErrorCodeKey = 8}}})
答案 0 :(得分:1)
服务器响应不包含任何缓存头,因此不会缓存任何内容。
如果要添加到缓存,则需要更改服务器发送的响应标头或手动将响应添加到缓存。完成后,您可以在请求上设置cachePolicy
来指示缓存的使用方式和时间(因为缓存可能已过期)。
let newCachedResponse = NSCachedURLResponse(response:response, data:response.data, userInfo:nil, storagePolicy:XXX)
NSURLCache.sharedURLCache().storeCachedResponse(newCachedResponse, forRequest:request)