具有AFNetworking和离线模式的SDURLCache无法正常工作

Eca*_*ion 37 iphone caching objective-c ios afnetworking

我使用的是AFNetworkingSDURLCache我所有的网络操作.

我这样SDURLCache设置:

SDURLCache *urlCache = [[SDURLCache alloc]
        initWithMemoryCapacity:1024*1024*2   // 2MB mem cache
        diskCapacity:1024*1024*15 // 15MB disk cache
        diskPath:[SDURLCache defaultCachePath]];
    [urlCache setMinCacheInterval:1];
    [NSURLCache setSharedURLCache:urlCache];
Run Code Online (Sandbox Code Playgroud)

我的所有请求都使用cachePolicy NSURLRequestUseProtocolCachePolicy,根据apple docs的工作原理如下:

如果请求不存在NSCachedURLResponse,则从原始源获取数据.如果请求的缓存响应,则URL加载系统会检查响应以确定它是否指定必须重新验证内容.如果必须重新验证内容,则会与原始源建立连接以查看其是否已更改.如果它没有更改,则从本地缓存返回响应.如果已更改,则从原始源获取数据.

如果缓存的响应未指定必须重新验证内容,则检查响应中指定的最大期限或到期时间.如果缓存的响应足够新,则从本地缓存返回响应.如果确定响应是陈旧的,则检查原始源是否有更新的数据.如果有更新的数据,则从原始源获取数据,否则从缓存返回.

因此,只要缓存不是陈旧的,即使在飞行模式下一切都能正常工作.当缓存过期(max-age和其他)时,将调用失败块.

我一直在挖掘内部SDURLCache,这个方法返回一个有效数据的响应(我已经将数据解析为一个字符串,它包含缓存的信息)

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
    request = [SDURLCache canonicalRequestForRequest:request];

    NSCachedURLResponse *memoryResponse =
        [super cachedResponseForRequest:request];
    if (memoryResponse) {
        return memoryResponse;
    }

    NSString *cacheKey = [SDURLCache cacheKeyForURL:request.URL];

    // NOTE: We don't handle expiration here as even staled cache data is
    // necessary for NSURLConnection to handle cache revalidation.
    // Staled cache data is also needed for cachePolicies which force the
    // use of the cache.
    __block NSCachedURLResponse *response = nil;
    dispatch_sync(get_disk_cache_queue(), ^{
        NSMutableDictionary *accesses = [self.diskCacheInfo
            objectForKey:kAFURLCacheInfoAccessesKey];
        // OPTI: Check for cache-hit in in-memory dictionary before to hit FS
        if ([accesses objectForKey:cacheKey]) {
            response = [NSKeyedUnarchiver unarchiveObjectWithFile:
                [_diskCachePath stringByAppendingPathComponent:cacheKey]];
            if (response) {
                // OPTI: Log entry last access time for LRU cache eviction
                // algorithm but don't save the dictionary
                // on disk now in order to save IO and time
                [accesses setObject:[NSDate date] forKey:cacheKey];
                _diskCacheInfoDirty = YES;
            }
        }
    });

    // OPTI: Store the response to memory cache for potential future requests
    if (response) {
        [super storeCachedResponse:response forRequest:request];
    }

    return response;
}
Run Code Online (Sandbox Code Playgroud)

所以在这一点上我不知道该怎么做,因为我相信响应是由操作系统处理然后AFNetworking接收到的

- (void)connection:(NSURLConnection *)__unused connection 
  didFailWithError:(NSError *)error
Run Code Online (Sandbox Code Playgroud)

在里面AFURLConnectionOperation.

Eca*_*ion 12

好吧,我终于达到了一个不那么丑陋的解决方法:

第一

如果你正在使用IOS5/IOS6,你可以删除SDURLCache并使用原生的:

//Set Cache
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
                                                     diskCapacity:20 * 1024 * 1024
                                                         diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
Run Code Online (Sandbox Code Playgroud)

但请记住,在IOS5中,https请求不会在IOS6中缓存.

第二

我们需要为我们添加以下框架,Prefix.pch因此AFNetworking可以开始监控我们的互联网连接.

#import <MobileCoreServices/MobileCoreServices.h>
#import <SystemConfiguration/SystemConfiguration.h>
Run Code Online (Sandbox Code Playgroud)

第三

我们需要和AFHTTPClient实例,所以我们可以拦截每个传出请求并更改他的 cachePolicy

-(NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters {

    NSMutableURLRequest * request = [super requestWithMethod:method path:path parameters:parameters];
    if (request.cachePolicy == NSURLRequestUseProtocolCachePolicy && self.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        request.cachePolicy = NSURLRequestReturnCacheDataDontLoad;
    }

    if (self.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown) {

        puts("uknown reachability status");
    }

    return request;
}
Run Code Online (Sandbox Code Playgroud)

有了这些代码和平,我们现在可以检测到wifi/3g何时不可用,并指定始终使用缓存的请求,无论如何.(离线模式)

笔记

  • 我仍然不知道该怎么办当这networkReachabilityStatusAFNetworkReachabilityStatusUnknown可能发生的是一旦应用程序启动并且AF尚未获得互联网状态的请求.

  • 请记住,为了使其工作,服务器必须在http响应中设置正确的缓存头.

UPDATE

看起来IOS6在无互联网情况下加载缓存响应时遇到一些问题,因此即使请求被缓存且请求缓存策略被设置NSURLRequestReturnCacheDataDontLoad为请求也将失败.

因此,一个丑陋的解决方法是修改(void)connection:(NSURLConnection __unused *)connection didFailWithError:(NSError *)errorAFURLConnectionOperation.m,如果请求失败,但只对特定的高速缓存策略检索缓存的响应.

- (void)connection:(NSURLConnection __unused *)connection
  didFailWithError:(NSError *)error
{
    self.error = error;

    [self.outputStream close];

    [self finish];

    self.connection = nil;

    //Ugly hack for making the request succeed if we can find a valid non-empty cached request
    //This is because IOS6 is not handling cache responses right when we are in a no-connection sittuation
    //Only use this code for cache policies that are supposed to listen to cache regarding it's expiration date
    if (self.request.cachePolicy == NSURLRequestUseProtocolCachePolicy ||
        self.request.cachePolicy == NSURLRequestReturnCacheDataElseLoad ||
        self.request.cachePolicy == NSURLRequestReturnCacheDataDontLoad) {

        NSCachedURLResponse * cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:self.request];
        if (cachedResponse.data.length > 0) {
            self.responseData = cachedResponse.data;
            self.response = cachedResponse.response;
            self.error = nil;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 好的,我直接从Apple获得了这方面的消息.我一直在与iOS技术讲座上的Apple工程师交谈.*我:*"......我想使用NSURLCache,现在它支持磁盘缓存...."*Apple家伙:*"不,你不会!" 然后他解释说,它不是针对明确的离线场景而设计的,它旨在加速Safari,不应该用于手动下载. - 那么为什么他们不在文档中写那个?本来可以节省我几个小时的生命. (2认同)