The Documents directory
Our app only runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents, for example, Documents
and Library
. Every app has its own document directory from which it can read and write data as and when needed. This Documents
directory allows you to store files and subdirectories created by your app. Now, we will create a sample project to understand the Document directories in much more depth.
Getting ready
Open Xcode and go to File | New | File and then navigate to iOS | Application | Single View Application. In the popup, provide the product name DocumentDirectoriesSample
.
How to do it...
Perform the following steps to explore how to retrieve the path of document directories:
- First, we will find out where in simulators and iPhones our document directories are present. To find the path, we need to write some code in our
viewDidLoad
method. Add the following line of code inviewDidLoad:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSLog(@"%@", documentsDirectory);
In the preceding code, first we fetch the existing path in our path's array. Now, we will take the first object of our path array in a string that means our string contains one path for our directory. This code will print the path for document directory of the simulator or device wherever you are running the code.
- To create the folder in
documentsDirectory
, run the following code:NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"]; if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
In the preceding code snippet, the
[documentsDirectory stringByAppendingPathComponent:@"/MyFolder"]
line will create our folder in theDocument
directory and the last code of NSFileManager will check whether thatdataPath
exists or not; if it does not exist, then it will create a new path. - Now, compile and run the project; you should be able to see the path of
Document
directories in your project console. This should look like the following screenshot: - Now, go to Finder; from the options, select Go to Folder and paste the
documentsDirectory
path from the console. This will navigate you to the Documents directory of the simulator. The Documents directory will look like the following screenshot:
See also
The Apple developer link for documents directories is as follows: