Reputation: 16416
I would like to have my api response json cached so that the user may continue to use the app in offline mode. However, the result is NOT being cached and the error alert is displayed as such when I turn off WiFi.
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
guard (data != nil) else {
self.showConnectionErrorAlert()
return
}
}
task.resume()
This is how I configured my 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
}
Here is response header when online:
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"; } })
Here is error when offline:
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}}})
Upvotes: 0
Views: 877
Reputation: 119031
The server response doesn't contain any cache headers, so nothing will be cached.
If you want to add to the cache then you need to change the response headers sent by the server or add the response to the cache manually. Once you do that you can set the cachePolicy
on the request to dictate how and when the cache should be used (as the cache may be out of date).
let newCachedResponse = NSCachedURLResponse(response:response, data:response.data, userInfo:nil, storagePolicy:XXX)
NSURLCache.sharedURLCache().storeCachedResponse(newCachedResponse, forRequest:request)
Upvotes: 1