Wednesday, September 5, 2012

How to Load/Save a file from/to the NSDocumentDirectory in an iOS application

This post is about loading and saving a file from and to the NSDocumentDirectory in an iOS application

Here we will declare two methods:-
-(void)loadFile; // to read file form the NSDocumentDirectory
-(void)saveFile; // to store file to the NSDocumentDirectory



Let us use an example of a .plist file named "your_file" which you hav created or added in your, lets say, Supporting Files folder in your xcode project. Lets use NSDictionary selectedObjectsDict to store the fetched .plist file.


NSDictionary * selectedObjectsDict;

-(void)loadPlistFile{
    BOOL success;
    NSError *error;
    NSString *filePath= [[NSBundle mainBundle] pathForResource:@"your_file" ofType:@"plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * path =[[NSString alloc] initWithString:
                                      [documentsDirectory stringByAppendingPathComponent:@"your_file.plist"]];
    
    success = [fileManager fileExistsAtPath:path];
    if (success) {
        self.selectedObjectsDict=[[NSMutableDictionary alloc] initWithContentsOfFile:path];       
        
    }
    else
    {    
        
        success = [fileManager copyItemAtPath:filePath  toPath:path error:&error];
        self.selectedObjectsDict=[[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
        
        
    }    
    
}

Here, filePath stores the path of your_file in your Xcode folder (not the path in NSDocumentDirectory). fileManager is a NSFileManager object which help you to perform many generic file-system operations for you. paths stores the array of strings which defines the path for different directories in domainsdocumentsDirectory stores the path for Documents directory which is the first object in the array pathsFinally, path stores the path to the file "your_file" which will be inside the Documents directory
Now the if else function checks if the file has already been saved to the Document directory. If TRUE is loads the selectedObjectsDict with the file your_file in Document directory else it copies the file your_file from filePath (i.e. the path for folder in the Xcode project) to path(i.e. the path for the NSDocumentDirectory ) and also loads the selectedObjectsDict with the same file.

Saving the file to the NSDocumentDirectory is almost similar and much easier. You just need to have the path where you want to save the file. The main work is done by the method-[file_to_be_saved writeToFile: path_to_be_used_to_save atomically:YES];



-(void)savePlistFile{
    [self.selectedObjectsDict setObject:self.selectedObjectsArray forKey:self.objectUID];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * path =[[NSString alloc] initWithString:
                                      [documentsDirectory stringByAppendingPathComponent:@"your_file.plist"]];
    [self.selectedObjectsDict writeToFile:path atomically:YES];
}


However, some may wants to rename the file in the directory. See this Rename the file in the NSDocumentDirectory



7 comments:

  1. Nice it seems to be good post... It will get readers engagement on the article since readres engagement plays an vital role in every blog.. i am expecting more updated posts from your hands.
    iOS Training in Chennai
    Android Training in Chennai
    php Training in Chennai

    ReplyDelete
  2. Hi,

    Thank you for sharing this coding, given both the coding is quite helpful and error free. You shared in details about the coding which is also efficient with the ios code review tools

    ReplyDelete

  3. Being new to the blogging world I feel like there is still so much to learn. Your tips helped to clarify a few things for me as well as giving..
    Android App Development Company

    ReplyDelete
  4. You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...
    iOS App Development Company
    iOS App Development Company

    ReplyDelete
  5. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    Fitness SMS
    Fitness Text
    Salon SMS
    Salon Text
    Investor Relation SMS
    Investor Relation Text
    Mobile Marketing Services
    mobile marketing companies
    Sms API

    ReplyDelete
  6. great and nice blog thanks sharing..I just want to say that all the information you have given here is awesome...Thank you very much for this one.
    web design Company
    web development Company
    web design Company in chennai
    web development Company in chennai
    web design Company in India
    web development Company in India

    ReplyDelete
  7. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Mobile Marketing Service
    Mobile Marketing Companies
    Sms API
    Texting API

    ReplyDelete