iOS 自定义NSURLCache缓存磁盘

iOS 自定义NSURLCache缓存磁盘

当系统内置的网络数据缓存处理机制不能满足需求时,我们需要定制缓存机制

自定义MyURLCache继承NSURLCache

重写这两个方法:

-(NSCachedURLResponse*) cachedResponseForRequest:(NSURLRequest *)request{
    
    NSString *url = [[request URL] absoluteString];        
        NSString *filename = [self getCacheFileName:url];        
        //先从内存取,内存有就直接返回了。
        NSCachedURLResponse *cachedResponse = [cachedResponseMap objectForKey:filename];
        if (cachedResponse)
        {
            return cachedResponse;
        }
        
        //内存中没有,尝试从磁盘加载缓存。
        BOOL isCacheExisted = [[NSFileManager defaultManager] fileExistsAtPath:[mCacheDir stringByAppendingPathComponent:filename]];
        if(isCacheExisted)
        {
            NSCachedURLResponse * response = [self loadCacheFromDisk:request localFile:filename];
            if(response != nil)
            {
                NSLog(@"get cache from disk");
                [cachedResponseMap setObject:response forKey:filename];
                return response;
            }
        }
    return [NSURLCache.sharedURLCache cachedResponseForRequest:request];
}
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request
{
    if (nil != cachedResponse) {
        NSString *url = [[request URL] absoluteString];

            NSLog(@"storeCachedResponse(%@)",url);
            NSString *filename = [self getCacheFileName:url];
            [self storeCacheToDisk:cachedResponse localFile:filename];
            [cachedResponseMap setObject:cachedResponse forKey:filename];
            return;
        }
        [NSURLCache.sharedURLCache storeCachedResponse:cachedResponse forRequest:request];
}

你可能感兴趣的:(iOS,NSURLCache,iOS,URL缓存)