如何在iOS的AFNetworking中增加缓存的到期时间

时间:2014-03-28 08:23:46

标签: ios caching afnetworking afnetworking-2

我需要下载并在单元格中显示图像,我正在使用

- (void)setImageWithURL:(NSURL *)url

方法,但有一段时间后,下载的图像会从单元格中消失并再次下载。我发现图像只能在缓存中保存30秒,但我想永远将它保存在缓存中,并希望通过调用函数来手动删除缓存以释放缓存。可能吗?

3 个答案:

答案 0 :(得分:0)

NSURLCache检查服务器标头,查看服务器的缓存策略以存储图像。还要确保缓存足够大以存储图像。如果图像大小大于5%(或其他),则高速缓存大小不会缓存图像。

由于AFNetworking使用默认NSURLCache,您最好的选择是继承NSURLCache。使用自定义版本的NSURLCache,您可以检查请求是否是图像,如果存储,则将其存储在您想要caches目录中的某个位置。

这样您可以像以前一样继续使用AFNetworking ./

答案 1 :(得分:0)

使用AFNetworking检索文件时永久处理文件的一种好方法是使用以下方法:

//Store the file
+ (void) cacheFile:(NSString *)fileName data:(NSData *)data
{
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName]; //add our image to the path
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL ok = [fileManager createFileAtPath:fullPath contents:data attributes:nil];

    if (!ok) {
        NSLog(@"Error creating file %@", fullPath);
    } else {
        NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:fullPath];
        [myFileHandle writeData:data];
        [myFileHandle closeFile];
    }
}

//Check if file is already stored
+ (BOOL) fileExistsInCache:(NSString *)fileName
{
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName];

    DLog(@"path to file's existance, %@", fullPath);

    return [[NSFileManager defaultManager] fileExistsAtPath:fullPath];
}

//Load file from storage
+ (NSData *) loadCachedFile:(NSString *)fileName
{
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName];

    DLog(@"path to file's existance, %@", fullPath);

    NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:fullPath];
    return [myFileHandle readDataToEndOfFile];
}

//Remove file from storage
+ (void) removeCachedFile:(NSString *)fileName
{   
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName];

    BOOL ok = [[NSFileManager defaultManager] removeItemAtPath:fullPath error:NULL];
}

//Find out what is already stored
+ (NSMutableArray *)returnAllCachedMediaFiles
{
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *dirContents = [fm contentsOfDirectoryAtPath:documentsDirectory error:nil];

    DLog(@"dirContents %@", dirContents);

    NSMutableArray *cachedMediaFiles = [[[NSMutableArray alloc] init] autorelease];

    for (NSString *fileName in dirContents) 
    {
        if ([fileName hasSuffix:@".png"] || [fileName hasSuffix:@".jpg"]) 
        {
            [cachedMediaFiles addObject:fileName];
        }
    }

    return cachedMediaFiles;
}

项目中的正确展示位置我不能说。但是,这些方法将为您提供足够的句柄。 请记住,使用了documentsDirectory,你可能想要使用自己的东西(比如NSCachesDirectory或其他)。

答案 2 :(得分:0)

这里获取图像的简单方法

- (void) cacheImage: (NSString *) ImageURLString
{
assert(nil != ImageURLString);

NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *myPath    = [myPathList  objectAtIndex:0];
NSString * fileName = [ImageURLString lastPathComponent];
NSString * uniquePath = [myPath stringByAppendingPathComponent:fileName];
// Check for file existence
if(![[NSFileManager defaultManager] fileExistsAtPath: uniquePath])
{
    // Fetch image from url and cache it
    NSData *data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:ImageURLString]];
    [data writeToFile:uniquePath atomically:YES];
}

}

- (UIImage *) getCachedImage: (NSString *) ImageURLString
{
assert(nil != ImageURLString);

// create unique path for image
NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *myPath    = [myPathList  objectAtIndex:0];
NSString * fileName = [ImageURLString lastPathComponent];
NSString * uniquePath = [myPath stringByAppendingPathComponent:fileName];

UIImage *image;

// Check for a cached version
if([[NSFileManager defaultManager] fileExistsAtPath: uniquePath])
{
    image = [UIImage imageWithContentsOfFile: uniquePath]; //this is the cached image
}
else
{
    // cache image and return cached image
    [self cacheImage: ImageURLString];
    image = [UIImage imageWithContentsOfFile: uniquePath];
}

return image;
}

通过调用第二种方法可以获得缓存图像,如果没有缓存,它将从URL获取并将其存储在文件中并将图像返回给您。我没有为它实现清理代码。