gpt4 book ai didi

iphone - NSURLCache 不缓存

转载 作者:太空狗 更新时间:2023-10-30 03:33:51 28 4
gpt4 key购买 nike

所以我对 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字符串和之前一样存储缓存响应。由于某种原因,它不是缓存。我已将缓存大小设置为一定大小。

最佳答案

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

关于iphone - NSURLCache 不缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8936488/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com