草庐IT

ios - NSCachedURLResponse willCacheResponse 不会被调用

coder 2024-01-14 原文

我们已经按照下面的简短代码片段设置了一个简单的 NSURLConnection 和 NSURLCache。我们已确保服务器 (localhost:9615) 返回以下缓存 header :

ETag : abcdefgh
Cache-Control : public, max-age=60

但是,永远不会调用 willCacheResponse 委托(delegate)方法。有什么想法吗?

代码:

// In the app delegate
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];

// Triggered by a UIButton
- (IBAction)sendRequest:(UIButton *)sender {
    NSLog(@"sendRequest");
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:9615"] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
    NSMutableData *receivedData = [NSMutableData dataWithCapacity: 0];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (!theConnection) {
        receivedData = nil;
    }
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    NSLog(@"willCacheResponse");
    // ...
}

最佳答案

Cocoa 应用各种标准来确定它是否可以缓存。例如,根据我的经验,如果响应大小超过持久存储缓存大小的大约 5%,您将不会看到 willCacheResponse 被调用。我还看到其他人声称如果 max-age 小于 1835400,它也不会缓存(这不是我的经验,但也许旧的 iOS 版本会受到影响由此)。显然,请求必须是 httphttps 请求,而不是 ftpfile 请求。

如果我的缓存足够大(并且我的响应正确地提供了 Cache-ControlContent-Type),我发现缓存工作正常。我只希望 Apple 能够清楚地阐明所应用的标准(在文档或返回代码中),因为我和其他人已经浪费了数小时来诊断缓存故障,结果才意识到 Cocoa 正在应用一些 secret 规则。

请注意,如果 NSURLConnection 本身满足于从缓存中检索它,则不会调用 willCacheResponse。当然,请确保未调用 didFailWithError

关于ios - NSCachedURLResponse willCacheResponse 不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20290580/

有关ios - NSCachedURLResponse willCacheResponse 不会被调用的更多相关文章

随机推荐