Monday, May 21, 2012

Reading & Writing Images from iPhone's Documents Directory


Hello,

Many a times we face situations where we want to save some images or files in phones documents directory and then retrieve them when needed.

This option is usually chosen to avoid  fetching contents from web server
 instead saving & fetching contents locally on user's iPhone.

I have created two functions hope it helps somebody :)



-(void)saveImageInPhone:(NSData*)imageData withName:(NSString*)iconName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory
                     NSUserDomainMask, YES);  


    //Get the docs directory
    NSString *documentsPath = [paths objectAtIndex:0]; 
    NSString *folderPath = [documentsPath
                            stringByAppendingPathComponent:@"IconImages"];
    
   if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:folderPath 
          withIntermediateDirectories:NO attributes:nil error:nil];
    
    //Add the FileName to FilePath
    NSString *filePath = [folderPath stringByAppendingPathComponent:[iconName 
                         stringByAppendingFormat:@"%@",@".png"]];

    //Write the file to documents directory
    [imageData writeToFile:filePath atomically:YES]; 
}




-(UIImage*)retrieveImageFromPhone:(NSString*)fileName 
                    havingVersion:(NSString*)iconVersionString 
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory
                     NSUserDomainMask, YES);  
    
    //Get the docs directory
    NSString *documentsPath = [paths objectAtIndex:0]; 

    NSString *folderPath = [documentsPath
                           stringByAppendingPathComponent:@"IconImages"];

    NSString *filePath = [folderPath stringByAppendingPathComponent:
                          [fileName stringByAppendingFormat:
                            @"%@",@".png"]];

    if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
        return [[UIImage alloc] initWithContentsOfFile:filePath];
    else 
        return nil;
}


How to view contents in Document Directory :


Finder  >> Library >> Application Support >> iPhone Simulator >> 
iOS version (5.1) >>  Applications >> Your Sample Application >> 
Documents >> IconImages >> myFirstImage.png.











2 comments:

  1. can you pls help me how can I save images into a folder
    thanks for advance

    ReplyDelete
  2. Extremely sorry for late reply, I am already saving images in Folder named : IconImages

    ReplyDelete