如何在iOS网络中增加缓存到期时间

如何在iOS网络中增加缓存到期时间,ios,caching,afnetworking,afnetworking-2,Ios,Caching,Afnetworking,Afnetworking 2,我需要下载和显示在手机和我使用的图像 - (void)setImageWithURL:(NSURL *)url 方法,但有时下载的图像会从单元格中消失并再次下载。我发现图像只能在缓存中保留30秒,但我想永远将其保存在缓存中,并想通过调用函数释放缓存来手动删除缓存。可能吗 检查服务器头以了解用于存储图像的服务器的缓存策略。还要确保缓存足够大以存储图像。如果图像大小大于5%(或其他),则不会缓存图像的缓存大小 因为使用默认值,所以最好的选择是子类化。使用自定义版本的,您可以检查请求是否为图像,如果

我需要下载和显示在手机和我使用的图像

- (void)setImageWithURL:(NSURL *)url
方法,但有时下载的图像会从单元格中消失并再次下载。我发现图像只能在缓存中保留30秒,但我想永远将其保存在缓存中,并想通过调用函数释放缓存来手动删除缓存。可能吗

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

因为使用默认值,所以最好的选择是子类化。使用自定义版本的,您可以检查请求是否为图像,如果是,请在
缓存
目录中存储所需的时间


通过这种方式,您可以按习惯继续使用。//p>使用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或其他任何内容)。

这里是获取图像的简单方法

- (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获取并存储在文件中,然后将图像返回给您。我没有为它执行清理代码。

这可能是肯定的。但它要求你把它储存在手机上,并在需要时从手机上取回。顺便说一句,考虑到你的问题,你的问题的标题相当混乱。您可能想更改它。但AFNetworking API中有任何方法吗?您是否在表视图单元格中设置图像?不,您必须自己编写(这样做并不困难)。不太可能。AFNetworking旨在从internet检索数据。在应用生命周期中,他不负责为您存储/缓存它。您可以保留AFNetworking lib,您只需要自己添加文件的缓存/存储部分。当您想要显示图像时,您只需首先检查它是否在缓存中,如果不在缓存中,则要求AFNetworking API延迟加载它(然后缓存/存储它。我可以给你一段代码,你可以在其中存储文件,如果你想的话。这段代码将永久存储文件。我认为AFR已经在做了,但不知道它将图像存储在哪里。请参阅此---------------------(void)setImageWithURL:(NSURL)url占位符图像:(UIImage*)占位符图像{NSMutableURLRequest*请求=[NSMutableUrlRequestWithURL:url];[request addValue:@“image/”forHTTPHeaderField:@“Accept”]------所有
NSURLConnection
/
nsurlcession
都使用
NSURLCache
。由于AFNetworking是在
NSURLConnection
/
nsurlcession
之上构建的,因此它们使用
NSURLCache
。因此,如果缓存太小,则不会缓存图像。如果希望缓存更长时间,则会缓存服务器头告诉
NSURLCache
它们应该被缓存。您必须编写自己版本的
NSURLCache