Copy a file to the Documents directory in iOS

This is a simple method that I use to copy a file from the app bundle to the Documents directory. You can’t modify files in the app bundle, but you can modify them if they are in the Documents directory.


- (void)createResultsDocument {
    
    NSString *documentsDirectory = [self applicationDocumentsDirectory];
    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"HTML_header.html"];
    
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *todaysDate = [dateFormatter stringFromDate:[NSDate date]];
    NSString *resultsFileName = [NSString stringWithFormat:@"MPResults_%@.html",todaysDate];
    NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:resultsFileName];
    NSError *error;
    
    [[NSFileManager defaultManager] copyItemAtPath:sourcePath 
                                            toPath:destinationPath
                                             error:&error];
    NSLog(@"The copy error is: %@", error);
    
    // Check that it worked.
    NSURL *resultsURL = [NSURL fileURLWithPath:destinationPath];
    NSLog(@"The resultsURL is: %@", resultsURL);
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.