您可以为此目的使用 NSURLCache。昨天我和这个一起工作,我上课:
@interface MyURLCache : NSURLCache
@property (nonatomic, assign) NSTimeInterval timeAvaiable;
@end
@implementation MyURLCache
- (id)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(NSString *)path
{
self = [super initWithMemoryCapacity:memoryCapacity diskCapacity:diskCapacity diskPath:path];
if(self){
_timeAvaiable = 5*60;//5 мин
}
return self;
}
- (id)init
{
self = [super init];
if(self){
_timeAvaiable = 5*60;
}
return self;
}
+ (NSCachedURLResponse*)addInfoDataToCachedResponce:(NSCachedURLResponse*)cachedResponse
{
NSMutableDictionary* newUserInfo = [@{@"LastUpdate" : @([[NSDate date] timeIntervalSince1970])} mutableCopy];
if([cachedResponse userInfo])
newUserInfo[@"UserInfo"] = [cachedResponse userInfo];
return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
data:[cachedResponse data]
userInfo:newUserInfo
storagePolicy:[cachedResponse storagePolicy]];
}
+ (NSCachedURLResponse*)removeInfoDataFromCachedResponce:(NSCachedURLResponse*)cachedResponse
{
return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
data:[cachedResponse data]
userInfo:[cachedResponse userInfo][@"UserInfo"]
storagePolicy:[cachedResponse storagePolicy]];
}
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
NSCachedURLResponse* result = [super cachedResponseForRequest:request];
NSDate* lastUpdate = [NSDate dateWithTimeIntervalSince1970:[result.userInfo[@"LastUpdate"] doubleValue]];
BOOL expired = fabs([lastUpdate timeIntervalSinceNow]) > _timeAvaiable;
return expired? nil : [[self class] removeInfoDataFromCachedResponce:result];
}
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request
{
[super storeCachedResponse:[[self class] addInfoDataToCachedResponce:cachedResponse] forRequest:request];
}
@end
并且在应用加载时启用缓存:
MyURLCache *URLCache = [[MyURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
diskCapacity:20 * 1024 * 1024
diskPath:[SDURLCache defaultCachePath]];
[NSURLCache setSharedURLCache:URLCache];
对于每个请求都需要将 cachePolicy 设置为 NSURLRequestReturnCacheDataElseLoad。
或者只是使用 AFNetworking :)
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;