应用程序关闭时,NSURLCache将被清空

时间:2014-12-27 17:35:58

标签: ios objective-c afnetworking nsurlcache

我试图用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仍为空...

1 个答案:

答案 0 :(得分:1)

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

或者,Apple documentation for this method州:

  

请注意

     

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

这可能只是预期的行为?