mardi 28 juin 2016

Storing and retrieving images from documents directory in tableView?


I am trying to store images from webservice in documents directory.For a stored image I want to load it from documents directory in table view. The images are accessible from a url such as :- http://Address/App/User/Image/Puegeot_E7

Fetching from webservice is successful however from the documents directory I keep getting null image.

- (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];
    NSData* data = UIImagePNGRepresentation(image);
    [data writeToFile:path atomically:YES];
 }
}

- (UIImage *)getImageFromURL:(NSString *)fileURL{
   UIImage * result;
   NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
   NSLog(@"data %@",data); //This returns (null)
   result = [UIImage imageWithData:data];
   return result;
}

In tableView this is how I am trying to load from documents directory.

- (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];

     }
   }

Aucun commentaire:

Enregistrer un commentaire