是否会阻止在NSURLCache中缓存具有响应头“Cache-Control:Private”的文件?

时间:2015-03-08 03:47:47

标签: ios caching uiwebview nsurlcache

是否会阻止在Cache-Control:Private中缓存带有响应标头NSURLCache的文件?共享缓存(如setSharedCacheNSURLCache.sharedCache())还是自定义缓存?

要展开,我需要在离线时访问UIWebView。这个WebView的源代码有多个与之关联的外部CSS和JS文件。我可以缓存网站的大部分内容(CSS等等到位),但它似乎没有缓存为网站提供重要信息的特定JavaScript文件。我在不缓存的文件与其余文件之间注意到的差异是它的Cache-Control设置为private(其他是公共的)。但是,根据我的阅读,将缓存控件设置为private是为了防止代理缓存。它会影响iOS上的缓存吗?

设置缓存

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
}

使用缓存

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")
            }
        }
    })
}

填充UIWebView

APICommunicator.sharedInstance.getWebPage({ htmlString, url in

    dispatch_async(dispatch_get_main_queue(),{
        self.webView.loadHTMLString(htmlString, baseURL: url)
    })

})

2 个答案:

答案 0 :(得分:1)

我最终创建了一个类似于NSURLConnectionDelegate方法willCacheResponse的方法,并替换了Cache-Control:private标题。

willCacheResponse方法

func willCacheResponse(cachedResponse: NSCachedURLResponse) -> NSCachedURLResponse?
{        
    let response = cachedResponse.response

    let HTTPresponse: NSHTTPURLResponse = response as NSHTTPURLResponse

    let headers: NSDictionary = HTTPresponse.allHeaderFields

    var modifiedHeaders: NSMutableDictionary = headers.mutableCopy() as NSMutableDictionary

    modifiedHeaders["Cache-Control"] = "max-age=604800"

    let modifiedResponse: NSHTTPURLResponse = NSHTTPURLResponse(
            URL: HTTPresponse.URL!,
            statusCode: HTTPresponse.statusCode,
            HTTPVersion: "HTTP/1.1",
            headerFields: modifiedHeaders)!

    let modifiedCachedResponse = NSCachedURLResponse(
            response: modifiedResponse,
            data: cachedResponse.data,
            userInfo: cachedResponse.userInfo,
            storagePolicy: cachedResponse.storagePolicy)

    return modifiedCachedResponse
}

通话方法

if let cachedResponse = self.willCacheResponse(
        NSCachedURLResponse(response: response,
                                data: data,
                            userInfo: nil,
                       storagePolicy: .Allowed)) {

    NSURLCache.sharedURLCache().storeCachedResponse(cachedResponse, forRequest: request)
}

现在它在离线状态下正确显示。多么美好的旅程。

答案 1 :(得分:0)

是的,NSURLCache没有缓存私有缓存控制策略的响应。 RFC #2616

  

私人:   表示响应消息的全部或部分用于单个用户,并且不得由共享高速缓存进行高速缓存。这允许源服务器声明指定的部分   响应仅适用于一个用户,并且不是其他用户请求的有效响应。私有(非共享)缓存可以缓存响应。

好吧,NSURLCache使用 sharedCache ,你甚至在你发布的代码中设置了它。我想它几乎解释了所有事情。

解决方案是更改服务器行为,或覆盖NSURLCache类的某些方法。 (你可以例如重写头部客户端,但这应该是一个非常糟糕的黑客。)

相关问题