What is the URL to the Documents Directory in iOS

I keep forgetting this time and time again. There is more than one way to slice a cake:

Option 1

This is how the Apple Templates with Core Data do it. This method takes a file name and returns its URL in the Documents Directory:

- (NSURL*)grabFileURL:(NSString *)fileName {
    // find Documents directory
    NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    // append a file name to it
    documentsURL = [documentsURL URLByAppendingPathComponent:fileName];

    return documentsURL;

// if you need the path instead
NSString *documentsPath = [documentsURL path];

Option 2

Here we make use of the foundation function NSHomeDirectory. This method takes a file name and returns its path in the Documents Directory:

- (NSString *)grabFilePath:(NSString *)fileName {
    NSString *filePath = [[NSString alloc]initWithFormat:@"Documents/%@", fileName];
    NSString *documentsFilePath = [NSHomeDirectory()stringByAppendingPathComponent:filePath];
    return documentsFilePath;

// and to convert that back into a URL:
NSURL *documentsURL = [NSURL fileURLWithPath:documentsFilePath];


If you don’t need to persist files you can make use of the NSTemporaryDirectory. Those files are not backed up and may be cleared by the OS when space is needed. It’s still good practice to delete them yourself if your app no longer needs them here.

Leave a Reply

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