我正在尝试使用以下方法加载图片。
我首先检查我是否已经在磁盘上有图像,如果我这样做,那么我将从磁盘上获取图像数据并加载它,否则我将从服务器获取图像并写入磁盘以便第二个我需要图像的时间,我不必访问服务器。
问题是它似乎没有从磁盘写入或读取。每当我想第二次加载图像时,它仍然从服务器读取它们,NSLog(@"disk");
永远不会被调用。
如果有人有任何想法,我不知道我做错了什么?
-(UIImage *)imageWith:(NSString *)imageName isPreview:(BOOL)preview
{
//imageName is something like "56.jpg"
NSString *mainOrPreview = @"Preview";
if (!preview) {
mainOrPreview = @"Main";
}
NSString *pathSuffix = [[@"Images" stringByAppendingPathComponent:mainOrPreview] stringByAppendingPathComponent:imageName];
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:pathSuffix];
NSData *imageData = [NSData dataWithContentsOfFile:path];
if (imageData) {
NSLog(@"disk");
}
if (!imageData && [self connected]) {
imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[serverURL stringByAppendingPathComponent: pathSuffix]]];
if (imageData) {
[imageData writeToFile:path atomically:YES];
}
NSLog(@"server");
}
return [UIImage imageWithData:imageData];
}
答案 0 :(得分:3)
问题是目录不存在于Documents
之外。因此,写入文件的尝试失败。使用具有NSError
参数的文件方法总是一个好主意,这样您就可以检查结果。
您只需要更新实际从服务器写入图像的代码。
if (!imageData && [self connected]) {
// This needs to be done in on a background thread!
imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[serverURL stringByAppendingPathComponent: pathSuffix]]];
if (imageData) {
[[NSFileManager defaultManager] createDirectoryAtPath:[path stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
[imageData writeToFile:path atomically:YES];
}
NSLog(@"server");
}