【问题标题】:NSURLCache is emptied when app is closed关闭应用程序时清空 NSURLCache
【发布时间】:2014-12-28 06:07:02
【问题描述】:

我正在尝试使用 AFHTTPRequestOperation 实现 NSURLCache,这就是我所做的:

AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:50 * 1024 * 1024 diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];

....
    }

然后使用它我这样做:

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0f];
UIImage *image = [[UIImageView sharedImageCache] cachedImageForRequest:urlRequest];
if (image != nil) {
  //Cached image
} else {

AFHTTPRequestOperation *postOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
postOperation.responseSerializer = [AFImageResponseSerializer serializer];
[postOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
  UIImage *image = responseObject;
  [[UIImageView sharedImageCache] cacheImage:image forRequest:urlRequest];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  NSLog(@"Image error: %@", error);
}];
[postOperation start];

}

当有上面的代码时我第一次打开视图时下载图像并将其存储在缓存中,然后我关闭视图并再次打开它并从缓存中读取它,而不是如果我关闭应用程序,我再次尝试再次下载图像,那么我如何创建一个 NSURLCache 持久化?

编辑:

我已经尝试了 Duncan Bubbage 的建议,我添加了一个缓存路径而不是 nil,我已经这样做了:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    cachePath = [cachePath stringByAppendingPathComponent:@"temp_img"];

    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:50 * 1024 * 1024 diskPath:cachePath];
    [NSURLCache setSharedURLCache:URLCache];

但我仍然无法在会话中永久缓存,我有什么问题?我还检查了 Finder 缓存文件夹,并且有 temp_img 文件夹,我尝试使用 NSFileManager 手动创建文件夹,然后传递路径,但文件夹 temp_img 保持为空...

【问题讨论】:

  • 在应用程序运行时是否有任何内容被写入缓存目录,然后被删除,或者只是没有写入任何内容?
  • 什么都没有写,没有目录,没有图像
  • 确保路径存在。
  • 如果我用 nsfilemanager 创建它肯定存在,但文件夹总是空的,而且文档说如果文件夹不存在,它将被创建,所以我认为这不是问题,谁能帮帮我?
  • 设置initWithMemoryCapacity:0是否有效?尝试将内存容量设置为与磁盘容量相同的大小。可能是内存容量阻止了缓存被使用。在这方面,您的问题在这里指出“当我第一次打开视图时,上面的代码下载图像并将其存储在缓存中”。但是,您是否确实确认过该图像曾经被缓存过,或者即使在当前的应用程序会话期间也会重新下载?可能只是你的缓存根本不工作。

标签: ios objective-c afnetworking nsurlcache


【解决方案1】:

当您想跨会话永久缓存到磁盘时,您确定设置diskPath:nil 有效吗?该参数是可选的,但这可能仅适用于仅在内存中缓存的用例,在这种情况下,您希望看到您在此处看到的内容?

或者,Apple documentation for this method 声明:

注意

在 iOS 中,当系统磁盘空间不足时,可能会清除磁盘缓存,但仅在您的应用未运行时才会清除。

这可能只是预期的行为吗?

【讨论】:

  • 感谢您的回答,我必须在系统运行低内存时清除磁盘缓存,还是 iOS 会自动清除?
  • 如果整个系统(不仅仅是缓存)的可用磁盘空间不足,iOS 会自动执行此操作。
  • 我已尝试添加路径,但不起作用,我已更新问题
猜你喜欢
  • 2017-07-27
  • 1970-01-01
  • 2012-03-23
  • 2022-01-09
  • 2019-03-29
  • 1970-01-01
  • 2011-06-17
  • 2013-05-01
  • 1970-01-01
相关资源
最近更新 更多