0

I've created folder called "Image store" using the following code. my requirment is i want to save images to the folder "Image store" on api success and the images should be saved in application itself not in database or photo album.I want to know the mechanism by which i can store images in application

-(void) createFolder {

   UIImage *image = [[UIImage alloc]init];

    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/ImageStore"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
    else
    {

    }
}
Shaik Riyaz
  • 11,204
  • 7
  • 53
  • 70
arshad
  • 267
  • 4
  • 11

4 Answers4

2
//Make a method that has url (fileName) Param 
NSArray *documentsDirectory =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);

NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];

NSFileManager *fileManager =[NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:textPath])
{
    return YES;
}
else
{
    return NO;
}

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage
imageNamed:@""]];//Placeholder image


if ([url isKindOfClass:[NSString class]])
{
    imgView.image = [UIImage imageNamed:[url absoluteString]];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
}
else if ([fileManager fileExistsAtPath:url])
{


    NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];

    NSError *error = nil;

    NSData *fileData = [NSData dataWithContentsOfFile:textPath options:NSDataReadingMappedIfSafe error:&error];

    if (error != nil)
    {
        DLog(@"There was an error: %@", [error description]);
        imgView.image=nil;
    }
    else
    {
        imgView.image= [UIImage imageWithData:fileData]
    }
}
else
{   UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
     initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];


    CGPoint center = imgView.center;
    //            center.x = imgView.bounds.size.width / 2;

    spinner.center = center;
    [spinner startAnimating];

    [imgView addSubview:spinner];


    dispatch_queue_t downloadQueue = dispatch_queue_create("iamge downloader", NULL);

    dispatch_async(downloadQueue, ^{

        NSData *imgData = [NSData dataWithContentsOfURL:url];

        dispatch_async(dispatch_get_main_queue(), ^{


            [spinner removeFromSuperview];

            UIImage *image = [UIImage imageWithData:imgData];


             NSError *error = nil;

[imgData writeToFile:url options:NSDataWritingFileProtectionNone error:&error];

if (error != nil)
{

}
else
{

}

            imgView.image = image;
        });
    });
}

Thats UIImageView loading an image if it doesnot exist in document then it Save it , An Activity indicator is added to show image is loading to save,

Zeeshan
  • 4,194
  • 28
  • 32
1

Write this code after creating directory

NSString *path= [documentsDirectory stringByAppendingPathComponent:@"/ImageStore"];
UIImage *rainyImage =[UImage imageNamed:@"rainy.jpg"];
NSData *Data= UIImageJPEGRepresentation(rainyImage,0.0);
[data writeToFile:path atomically:YES]
Jay Gajjar
  • 2,661
  • 2
  • 21
  • 35
  • [data writeToFile:path atomically:YES] what is 'path' here?? or is it should be like [Data writeToFile:datapath atomically:YES] – arshad Jan 13 '14 at 05:18
1

u can do something like this u can run a loop for images like this

  //at this point u can get image data
  for(int k = 0 ; k < imageCount; k++)
  {
     [self savePic:[NSString stringWithFormat:@"picName%d",k] withData:imageData];//hear data for each pic u can send
  }


 - (void)savePic:(NSString *)picName withData:(NSData *)imageData
   {
     if(imageData != nil)
     {
      NSString *path = [NSString stringWithFormat:@"/ImageStore/%@.png",pincName];
      NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
      NSString *pngPath = [NSString stringWithFormat:@"%@%@",Dir,path]; //path means ur destination contain's  this format -> "/foldername/picname" pickname must be unique
     if(![[NSFileManager defaultManager] fileExistsAtPath:[pngPath stringByDeletingLastPathComponent]])
     {
         NSError *error;
         [[NSFileManager defaultManager] createDirectoryAtPath:[pngPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&error];
         if(error)
         {
             NSLog(@"error in creating dir");
         }
     }
     [imageData writeToFile:pngPath atomically:YES];
  }
 }


after successful download and saving u can retrieve images like below


- (UIImage *)checkForImageIn:(NSString *)InDestination
  {

    NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *pngPath = [NSString stringWithFormat:@"%@%@",Dir,InDestination];//hear "InDestination" format is like this "/yourFolderName/imagename" as i said imagename must be unique .. :) 


    UIImage *image = [UIImage imageWithContentsOfFile:pngPath];
    if(image)
   {
      return image;
   }
   else
    return nil;
 }


link to find path see this link to find the path ..

aganin do same this run loop like below

  NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
  for(int k = 0 ; k < imageCount; k++)
    {
       UIImage *image = [self checkForImageIn:[NSString stringWithFormat: @"/yourFolderName/ImageName%d",k]];//get the image 
       [imagesArray addObject:image];//store to use it somewhere ..
    }
Community
  • 1
  • 1
Shankar BS
  • 8,394
  • 6
  • 41
  • 53
  • i've more than ten images.how can i do that? – arshad Jan 13 '14 at 05:33
  • how can i know if the image is stored in the folder? – arshad Jan 13 '14 at 06:16
  • go to application folder in the simulator there is folder created with ur folder name inside that ur downloaded images ... :) run this code anywhere "NSLog(@"path:%@",[[NSBundle mainBundle]bundlePath]);" to know path – Shankar BS Jan 13 '14 at 06:19
  • am sorry..am new to the iphone..how do u find application folder in simulator..? – arshad Jan 13 '14 at 06:24
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/45087/discussion-between-shan-and-arshad) – Shankar BS Jan 13 '14 at 06:29
1

The document directory is found like this:

// Let's save the file into Document folder. 
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

// If you go to the folder below, you will find those pictures
NSLog(@"%@",docDir);

NSLog(@"saving png");
NSString *pngFilePath = [NSString stringWithFormat:@"%@/test.png",docDir];

Thats just a sample of the code provided which tells you where the correct path is to save in your ipone device.

Check the below blog post,it's step by step guide with source code .

Download an Image and Save it as PNG or JPEG in iPhone SDK

Pavan
  • 17,840
  • 8
  • 59
  • 100