Would a file with a response header Cache-Control:Private
be prevented from being cached in a NSURLCache
? Either a shared cache (as in setSharedCache
and NSURLCache.sharedCache()
) or a custom one?
To expand, I have UIWebView
that I need to access when offline. The source of this WebView
has multiple external CSS and JS files associated with it. I can cache most of the site (the CSS, etc looks in place), however it seems to not be caching a specific JavaScript file that provides important information for the site. A difference that I noted between the file that won't cache and the rest is that it's Cache-Control is set to private (the others are public). However, from what I have read, setting the cache control to private is to prevent caching on proxies. Would it affect caching on iOS?
Setting up the cache
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let URLCache: NSURLCache = NSURLCache(memoryCapacity: 10 * 1024 * 1024,
diskCapacity: 50 * 1024 * 1024,
diskPath: nil)
NSURLCache.setSharedURLCache(URLCache)
println("Disk cache usage: \(NSURLCache.sharedURLCache().currentDiskUsage)")
// http://stackoverflow.com/questions/21957378/how-to-cache-using-nsurlsession-and-nsurlcache-not-working
sleep(1)
return true
}
Using the cache
func getWebPage(onCompletion: (NSString, NSURL) -> Void) {
let url = getApplicationSelectorURL()
let request = NSURLRequest(URL: url, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: 10.0)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: { response, data, error in
println("Web page task completed")
var cachedResponse: NSCachedURLResponse
if (error != nil) {
println("NSURLConnection error: \(error.localizedDescription)")
if let cachedResponse = NSURLCache.sharedURLCache().cachedResponseForRequest(request) {
if let htmlString = NSString(data: cachedResponse.data, encoding: NSUTF8StringEncoding) {
onCompletion(htmlString, url)
} else {
println("htmlString nil")
}
} else {
println("cacheResponse nil")
}
} else {
cachedResponse = NSCachedURLResponse(response: response, data: data, userInfo: nil, storagePolicy: .Allowed)
NSURLCache.sharedURLCache().storeCachedResponse(cachedResponse, forRequest: request)
if let htmlString = NSString(data: data, encoding: NSUTF8StringEncoding) {
onCompletion(htmlString, url)
} else {
println("htmlString nil")
}
}
})
}
Populating the UIWebView
APICommunicator.sharedInstance.getWebPage({ htmlString, url in
dispatch_async(dispatch_get_main_queue(),{
self.webView.loadHTMLString(htmlString, baseURL: url)
})
})