自定义NSProtocol和iPhone上的缓存问题

时间:2010-03-11 18:55:23

标签: iphone caching uiwebview nsurlcache nsurlprotocol

我的iPhone应用程序嵌入了一个UIWebView,它通过我注册的自定义NSProtocol处理程序加载html。

我的问题是返回的html中引用的资源(也是通过我的自定义协议处理程序加载的)被缓存并且从不重新加载。特别是,我的样式表被缓存:

    <link rel="stylesheet" type="text/css" href="./styles.css" /> 

在UIWebView中加载html的初始请求如下所示:

    NSString* strUrl = [NSMutableString stringWithFormat: @"myprotocol:///entry?id=%d", entryID ];
    NSURL* url = [NSURL URLWithString: strUrl];
    [_pCurrentWebView loadRequest: [NSURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 60 ]];

(请注意,缓存策略设置为忽略,我已验证此缓存策略会在初始加载时继续执行页面资源的后续请求)

协议处理程序从数据库加载html并使用以下代码将其返回给客户端:

    // create the response record
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL: [request URL] MIMEType: mimeType expectedContentLength: -1 textEncodingName: textEncodingName];

    // get a reference to the client so we can hand off the data
    id client = [self client];

    // turn off caching for this response data
    [client URLProtocol: self didReceiveResponse:response cacheStoragePolicy: NSURLCacheStorageNotAllowed];

    // set the data in the response to our jfif data  
    [client URLProtocol: self didLoadData:data];
    [data release];

(注意响应缓存策略是“不允许的”)。

我有什么想法可以让它不缓存我的styles.css资源?我需要能够在后续加载引用此文件的html时动态更改此资源的内容。

我认为清除共享URL缓存会起作用,但它不会:

[[NSURLCache sharedURLCache] removeAllCachedResponses];

有一件事可行,但效率非常低,是通过添加时间戳参数来动态缓存 - 破坏样式表的url:

<link rel="stylesheet" type="text/css" href="./styles.css?ts=1234567890" /> 

为了完成这项工作,我必须从数据库加载我的html,搜索并用每个请求更改的缓存清除参数替换样式表的url。我宁愿不这样做。

我的假设是,如果我通过内置的HTTP协议加载我的内容,则没有问题。在这种情况下,我猜测UIWebView会查看NSURLHTTPResponse对象的http标头中的任何Cache-Control标志并遵守它们。由于我的NSURLResponseObject没有http头(它不是http ...),所以UIWebView可能只是决定缓存资源(忽略NSURLRequest缓存指令?)。

思想???

0 个答案:

没有答案