Question
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?
Answer
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:
iOS 8 and newer, this is the recommended method
+ (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
if you need to support iOS 7 or earlier
+ (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]