iOS可以从磁盘写入或读取图像数据
我正在尝试使用以下方法加载图像 我首先检查磁盘上是否已经有图像,如果有,我将从磁盘上获取图像数据并加载它,否则我将从服务器获取图像并写入磁盘,以便第二次需要图像时,我不必访问服务器iOS可以从磁盘写入或读取图像数据,ios,uiimage,disk,Ios,Uiimage,Disk,我正在尝试使用以下方法加载图像 我首先检查磁盘上是否已经有图像,如果有,我将从磁盘上获取图像数据并加载它,否则我将从服务器获取图像并写入磁盘,以便第二次需要图像时,我不必访问服务器 if (!imageData && [self connected]) { // This needs to be done in on a background thread! imageData = [NSData dataWithContentsOfURL:[NSURL URLW
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");
}
问题是它似乎没有从磁盘写入或读取。每次我想第二次加载映像时,它仍然会从服务器和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];
}
问题是目录不存在于文档之外。因此,写入文件的尝试失败。最好使用具有NSError
参数的file方法,以便检查结果
您只需要更新实际从服务器写入映像的代码
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");
}
天啊!你真是个天才!你刚刚救了我。非常感谢你。