【发布时间】: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