【问题标题】:NSURLCache not cachingNSURLCache 不缓存
【发布时间】:2012-11-26 15:21:34
【问题描述】:

所以我对NSURLCache 进行了子类化,每次我调用loadHTMLFromString: 时,它都会调用storeCachedRequest:forRequest:,然后是cachedResponseForRequest:。这是我所拥有的:

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
    NSString *pathString = [[request URL] absoluteString];

    NSCachedURLResponse * response = [super cachedResponseForRequest:request];
    if (response != nil)
        return response;
    else {
        NSString* myString= @"testing";

        NSData* data=[myString dataUsingEncoding: NSASCIIStringEncoding ];

        //
        // Create the cacheable response
        //
        NSURLResponse *response =
        [[[NSURLResponse alloc]
          initWithURL:[request URL]
          MIMEType:[self mimeTypeForPath:pathString]
          expectedContentLength:[data length]
          textEncodingName:nil]
         autorelease];
        NSCachedURLResponse * cachedResponse =
        [[[NSCachedURLResponse alloc] initWithResponse:response data:data] autorelease];

        [self storeCachedResponse:cachedResponse forRequest:request] ;

        //NSLog(@"DEFAULT CACHE WITH URL %@", [[request URL] absoluteString]);
        return [super cachedResponseForRequest:request];
    }

    return nil;
}

- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request
{
    [super storeCachedResponse:cachedResponse forRequest:request];

    NSLog(@"STORE CACHED RESPONSE WITH URL %@", [[request URL] absoluteString]);
}

问题是当我在保存后立即调用cachedResponseForRequest: 时,响应始终为零。这是为什么呢?

我有:

NSURLRequest * req = [NSURLRequest requestWithURL:[NSURL URLWithString:self.imageSource_]];
NSCachedURLResponse * response = [[NSURLCache sharedURLCache] cachedResponseForRequest:req];

if (response == nil)
    NSLog(@"RESPONSE IS NIL");
else {
    NSString* theString = [[NSString alloc] initWithData:response.data encoding:NSASCIIStringEncoding];
    NSLog(@"RESPONSE IS NOT NIL %@", theString);
}

它总是打印 response is nil。 url 字符串和它之前的一样 storeCachedResponse。由于某种原因,它没有缓存。我已将缓存大小设置为一定大小。

【问题讨论】:

    标签: iphone objective-c ipad nsurlcache


    【解决方案1】:

    不是 100% 确定,但我认为您需要使用 NSURLConnection 返回的 NSURLResponse,而不是创建自己的。我的怀疑是,如果您只是创建一个 NSURLResponse 它没有为缓存设置任何标头,因此 NSURLCache 假设它应该缓存这个特定的结果。

    【讨论】:

    • 嗯...你确定吗?因为在该方法中,在 cachedResponseForRequest 和 response == nil 之前调用了 storeCachedResponse
    • 所以即使我没有创建自己的 NSURLResponse,它仍然不会保存它
    • “嗯……你确定吗?”再读一遍我回答的前三个字。 ;-)
    • 您的服务器是否发送了正确的缓存标头?
    • 是的,无论如何我决定只使用 SDURLCache 并且效果更好
    【解决方案2】:

    在选择要缓存的内容时,默认的 NSURLCache 似乎非常随机。您最好的选择可能是对其进行子类化并直接在 cachedResponseForRequest: 中处理您关心的文件的缓存,并将其余部分留给 super。

    【讨论】:

      猜你喜欢
      • 2014-09-27
      • 1970-01-01
      • 2014-01-28
      • 2013-09-05
      • 1970-01-01
      • 2011-10-11
      • 2016-12-08
      • 2014-03-24
      • 1970-01-01
      相关资源
      最近更新 更多