所以我创建了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);
}并且它总是打印出响应为空。url字符串与storeCachedResponse时相同。由于某些原因,它不是缓存。我已经将缓存大小设置为一定的大小。
发布于 2012-01-20 11:56:58
不是100%确定,但我认为你需要使用你的NSURLConnection返回的NSURLResponse,而不是创建你自己的。我怀疑如果只是创建一个NSURLResponse,它没有为缓存设置任何标头,因此NSURLCache假设它应该缓存这个特定的结果。
发布于 2012-11-26 15:21:34
在选择要缓存或不缓存的内容时,默认NSURLCache似乎是相当随机的。你最好的办法可能是将其子类化,并直接在cachedResponseForRequest中处理你所关心的文件的缓存,剩下的留给超级用户来处理。
https://stackoverflow.com/questions/8936488
复制相似问题