Can someone explain to me what the documents directory is on an iOS app and when to use it?
Here is what I believe at present:
To me, it seems to be a central folder where the user can store any files needed for the app.
This would be a different location than where Core Data stores its data?
It seems like each app gets its own documents directory.
I am free to create a subdirectory of the documents directory, like documents directory/images, or documents directory/videos?
Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.
See the iOS Application Programming Guide.
To access the Documents directory of your applications sandbox, you can use the following:
+ (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
+ (NSString *) applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = paths.firstObject;
return basePath;
}
This Documents directory allows you to store files and subdirectories your app creates or may need.
To access files in the Library directory of your apps sandbox use (in place of paths
above):
[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]
I have discovered that [@"~/Documents" stringByExpandingTildeInPath] does the same thing. Is there any reason that this should be discouraged?
I wouldn't use the approach with @"~/Documents". Hardcoding paths is never a good idea. It may work now, but if Apple ever chooses to rename or move the Documents directory, your app will break.
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
will always give you the correct directory!you should still use the provided API. That's why it's there! You've just been lucky until now.
Hilarious how I need to google this each time I have to use it. I think all mobile platforms should provide default global parameter for the home/writable directory
updated link with info on an app's ability to write to folders: developer.apple.com/library/mac/documentation/FileManagement/…