NSURLCache - 参数不起作用的GET请求的磁盘缓存

问题描述 投票:3回答:3

我正在尝试使用NSURLCache将一些HTTP请求缓存到磁盘。在使用AFNetworking进行一些测试并且无法工作之后,我使用NSURLRequest创建了一个简单的示例。

我像这样初始化AppDelegate上的缓存,将内存大小设置为0,强制它始终转到磁盘:

NSUInteger sz = 1024*1024*20;
NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:sz diskPath:nil];
[NSURLCache setSharedURLCache:cache];

我使用以下代码存储响应:

NSURLCache * urlCache = [NSURLCache sharedURLCache];

NSString *urlString = @"http://localhost:8000/cities/api/cities/?lang=en";
NSHTTPURLResponse *response = nil;
NSError *error = nil;

NSURL *finalUrl = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalUrl];
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;

NSData *data = nil;

data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:data userInfo:nil storagePolicy:NSURLCacheStorageAllowed];
[urlCache storeCachedResponse:cachedResponse forRequest:request];

我的请求有HTTP Header Cache-Control,如:

response ['cache-control'] ='max-age = 36000,public'

我看到响应缓存在Cache.db文件中。

然后,在下一次执行中或者甚至在同一个执行中,我使用以下代码尝试从缓存中获取响应:

NSCachedURLResponse *cachedResponse = [urlCache cachedResponseForRequest:request];
response = cachedResponse.response;
data = cachedResponse.data;

问题是当请求具有GET参数时,cachedResponse始终为null。如果请求是“http://localhost:8000/cities/api/cities/”,则结果将被存储并在以后恢复。但是当它确实有GET参数时,某些东西阻止了[NSURLCache cachedResponseForRequest:request]方法找到请求。

为此,我将NSURLCache子类化并实现了这样的方法:

- (id)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(NSString *)path {
self = [super initWithMemoryCapacity:memoryCapacity diskCapacity:diskCapacity diskPath:path];
if (self) {
    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *dir = (NSString*)[docPaths objectAtIndex:0];
    dir = [dir stringByAppendingString:@"/uk.co.airsource.TestURLCache/nsurlcache"];
    NSString *path = [dir stringByAppendingFormat:@"/Cache.db"];
    self.db = [[FMDatabase alloc] initWithPath:path];
    [self.db open];
    int o = 4;
}
return self;

}

- (NSCachedURLResponse *) cachedResponseForRequest:(NSURLRequest *)request {
NSCachedURLResponse *cachedURLResponse = [super cachedResponseForRequest:request];
if (cachedURLResponse == nil && [request.HTTPMethod isEqualToString:@"GET"]) {
    //[db executeQuery:@"select * from test where a = ?", @"hi'",  nil];
    NSLog(@"%@", request.URL.absoluteString);
    FMResultSet *cfurl_cache_response = [self.db executeQuery:@"select * from cfurl_cache_response where request_key = ? limit 1", request.URL.absoluteString, nil];
    if ([cfurl_cache_response next]) {
        id entry_ID = [cfurl_cache_response objectForColumnName:@"entry_ID"];
        [cfurl_cache_response close];
        if (entry_ID != [NSNull null]) {
            FMResultSet *cfurl_cache_blob_data = [self.db executeQuery:@"select * from cfurl_cache_blob_data where entry_ID = ? limit 1", entry_ID, nil];
            if ([cfurl_cache_blob_data next]) {
                id response_object = [cfurl_cache_blob_data objectForColumnName:@"response_object"];
                [cfurl_cache_blob_data close];
                FMResultSet *cfurl_receiver_data = [self.db executeQuery:@"select * from cfurl_cache_receiver_data where entry_ID = ? limit 1", entry_ID, nil];
                if ([cfurl_receiver_data next]) {
                    id receiver_data = [cfurl_receiver_data objectForColumnName:@"receiver_data"];
                    [cfurl_receiver_data close];
                    if (response_object != [NSNull null] && receiver_data != [NSNull null] && response_object && receiver_data) {
                        NSURLResponse *urlResponse = [[NSURLResponse alloc] initWithURL:request.URL MIMEType:[[request allHTTPHeaderFields] objectForKey:@"Accept"] expectedContentLength:[(NSData *)response_object length] textEncodingName:nil];
                        cachedURLResponse = [[NSCachedURLResponse alloc] initWithResponse:urlResponse data:receiver_data userInfo:nil storagePolicy:NSURLCacheStorageAllowed];
                    }
                }
            }
        }
    }
}
return cachedURLResponse;

}

在这种情况下,在带参数的GET请求下,它确实跟随每一行,直到获得之前缓存的NSURLResponse。

当请求具有GET参数时,有关为什么它不能正常工作的任何想法?

ios objective-c nsmutableurlrequest nsurlcache
3个回答
1
投票

问题似乎是没有指定内存容量,如果您指定内存容量如下,

在这里,我将内存容量指定为1 MB的大小

[[NSURLCache alloc] initWithMemoryCapacity:1*1024*1024 diskCapacity:sz diskPath:nil];

它会工作,在我看来,无论是否需要内存容量,容量有多小但不能为空。然后,您将能够提取存储的缓存,如下所示,

NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
response = cachedResponse.response;
data = cachedResponse.data;

0
投票

最后,我覆盖了NSURLCache,以便能够实现我的目标:

  1. GET请求(带参数)缓存到磁盘
  2. 请求缓存而“Cache-Control max-age”值表示它未过期,并在到期后再次访问服务器,存储新响应并开始过期时间
  3. 如果脱机,则始终从缓存中返回响应(如果存在)

NTURLCache - overrides NSURLCache

我认真地认为这是一个在iOS 8.1中无法正常工作的问题


0
投票

问题仍然存在于iOS 11.x,尽管我有一个iPad Mini运行版iOS 9.3.5,它具有完美的工作缓存。用NSURLCache/URLCache定义了一些东西

© www.soinside.com 2019 - 2024. All rights reserved.