您可以使用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;
參見[這裏] [1]的問題。它解釋了將圖像保存到緩存的鋤頭。 [1]:http://stackoverflow.com/questions/9289672/how-to-store-images-in-cache – Durgaprasad