iOS recipe : Storing local files in iPhone

Each iPhone iOS application on a device has its own private Documents and tmp directories into which it is permitted to read and write data. Because the location of these directories is different for each application the only way to find the correct path is to ask the iOS for the correct path.

The following code snippet will generate a file path that points to the private document directory private to your iOS app.

NSString *fileName = @"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

 When executed within the iOS Simulator environment, the path returned will take the form of:
/Users/<user name>/Library/Application Support/iPhone Simulator/<sdk version>/Applications/<app id>/Documents

Where <user name> is the name of the user currently logged into the Mac OS X system on which the simulator is running, <sdk version> is the version of the iOS SDK used to compile the application and <app id> is the unique ID of the app, for example:

06A3AEBA-8C34-476E-937F-A27BDD2E450A

Clearly this references a path on your Mac OS X system so feel free to open up a Finder window and explore the file system sandbox areas for your iOS iPhone applications.

When executed on a physical iPhone device, the path returned by the function call will take the following form:

/var/mobile/Applications/<app id>/Documents

Identifying the Temporary Directory

In addition to the Documents directory, iOS iPhone applications are also provided with a tmp directory for the storage of temporary files. The path to the current application’s temporary directory may be ascertained with a call to the NSTemporaryDirectory C function as follows:

NSString *tmpDir = NSTemporaryDirectory();

Once executed, the string object referenced by tmpDir will contain the path to the temporary directory for the application.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s