【问题标题】:iOS can write or read from image data from diskiOS 可以从磁盘写入或读取图像数据
【发布时间】:2013-05-13 21:07:44
【问题描述】:

我正在尝试使用以下方法加载图像。

我首先检查磁盘上是否已经有图像,如果有,我将只从磁盘获取图像数据并加载它,否则我将从服务器获取图像并写入磁盘,以便第二个当我需要图像时,我不必访问服务器。

问题是它似乎没有从磁盘写入或读取。每次我想第二次加载图像时,它仍然会从服务器读取它们,并且永远不会调用 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];
}

【问题讨论】:

    标签: ios uiimage disk


    【解决方案1】:

    问题是目录在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");
    }
    

    【讨论】:

    • 天啊!你是个天才!你刚刚救了我。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2017-10-12
    • 2015-07-19
    相关资源
    最近更新 更多