繁体   English   中英

从tableView的文档目录中存储和检索图像?

[英]Storing and retrieving images from documents directory in tableView?

我正在尝试将Web服务中的图像存储在documents目录中。对于存储的图像,我想从表格视图的documents目录中加载它。 可从以下网址访问图像: http://Address/App/User/Image/Puegeot_E7

从webservice获取成功,但是从documents目录中我一直得到空图像。似乎在这里找不到问题。

- (void)saveImage:(UIImage*)image withName:(NSString *)imageName
{
    if (image != nil)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent:imageName];

        NSLog(@"Saving path %@",path); // Saving path /Users/computername/Library/Developer/CoreSimulator/Devices/7277F3D3-298C-451A-8607-8070A08650C7/data/Containers/Data/Application/D3AF4DD9-A4CD-42C8-A8EB-0F15C271EE61/Documents/CabImage/Puegeot_E7

        NSData* data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];
    }
}

- (UIImage *)getImageFromURL:(NSString *)fileURL
{
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *path = [documentsDirectory stringByAppendingPathComponent:fileURL];
   NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:path]];
   NSLog(@"data %@",data); //This returns (null)
   UIImage *result = [UIImage imageWithData:data];
   return result;
}

在tableView中,这就是我尝试从documents目录加载的方式。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   //default initialisation stuff
   NSDictionary *obj = [responseArray objectAtIndex:indexPath.row];
   cell.imgVW.image = [UIImage imageNamed:@"default-car.png"];
   NSString *imgPath = obj[@"cabimage"];
   NSLog(@"imgPath : %@",imgPath); // imgPath : Image/Puegeot_E7 
   UIImage *imgFromDisk = [self getImageFromURL:imgPath];
   NSLog(@"imgFromDisk - %@",imgFromDisk); -> (null)
   if (imgFromDisk) 
   {
       cell.imgVW.image = imgFromDisk;
   }
   else
   {
       //download
       NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@User/%@",BASE_URL,imgPath]];

       self.task = [self.session downloadTaskWithURL:imageURL 
                   completionHandler:^(NSURL *location,NSURLResponse *response,NSError *error)
       {
            NSData *img_data = [NSData dataWithContentsOfURL:imageURL];
            if (img_data) 
            {
                 UIImage *img = [UIImage imageWithData:img_data];
                 dispatch_async(dispatch_get_main_queue(), ^{
                    ListCell *cell = (id)[tableView cellForRowAtIndexPath:indexPath];
                    cell.imgVW.image = img;                                 
                    [self saveImage:img withName:imgPath];

                });
            }
       }];
       [self.task resume];
   }
}

从日志中看到的问题似乎很明显:

NSLog(@"imgPath : %@",imgPath); // imgPath : Image/Puegeot_E7

该路径不在documents目录中。

为了对此进行更严格的控制,请使用save方法返回保存图像的路径:

- (NSString *)saveImage:(UIImage*)image withName:(NSString *)imageName{
    // op code, then:
    return path;
}

测试您是否可以读回图像。 (此代码用于测试,不适用于应用程序)。

UIImage *testImage = [UIImage imageNamed:@"some_test_image"];
NSString *path = [self saveImage:testImage withName:@"test_name"];
UIImage *didItWork = [self getImageFromURL:path];
NSLog(@"did it work? %@", didItWork);

返回真实的应用程序...在模型中写入图像返回的路径之后:

UIImage *downloadedImage = // however you get this
NSString * downloadedImageName = // however you get this
NSDictionary *obj = [responseArray objectAtIndex:indexPath.row];
obj[@"cabbage"] = [self saveImage: downloadedImage withName:downloadedImageName];

现在我们知道您的cellForRowAtIndexPath方法将看到已保存的路径,并且从测试中我们知道从该路径创建图像将起作用。

您得到nil是因为您没有提供正确的图像检索路径。 您仅使用图像的名称,但应使用与保存图像相同的路径。

所以说:

NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:imageName];

在您的getImageFromURL方法中。

不要只使用图像名称来检索图像。 希望这可以帮助!

(很抱歉,我的文字格式不好,我在手机上打字)

首先,建议您使用SDWebImage库-具有缓存支持的异步图像下载器。 使用非常简单:

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                ... completion code here ...
                             }];

但是,如果您希望按照自己的方式做。 您应该更改sss 2行代码:

UIImage *imgFromDisk = [self getImageFromURL:imgPath];

到这个:

UIImage *imgFromDisk = [self getImageFromURL:[imgPath lastPathComponent]];

[self saveImage:img withName:imgPath];

到这个:

[self saveImage:img withName:[imgPath lastPathComponent]];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM