What's the best way to find the user's Documents directory on an iPhone?

IosObjective CIphoneCocoa Touch

Ios Problem Overview


I'm reading Erica Sadun's iPhone Developer's Cookbook, and ran into a question.

She says in the book that the way to find the user's Documents directory is with the code:

[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

but that seems slightly brittle, and dissimiliar to the normal Mac way of doing it, which would be:

NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);

Are there any particular reasons to use one over the other?

Ios Solutions


Solution 1 - Ios

Objc:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)

Swift:

var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)

You'll want the first element of the returned array.

Solution 2 - Ios

Here is the code that I use in my framework.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

Solution 3 - Ios

You should consider using the FileManager methods which return URLs, which are the preferred format.
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first

This method is intended to locate known and common directories in the system.

An array of URL objects identifying the requested directories. The directories are ordered according to the order of the domain mask constants, with items in the user domain first and items in the system domain last.

Solution 4 - Ios

I use this

NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *zipLocalPath = [documentPath stringByAppendingString:fileName];

Solution 5 - Ios

In swift v3, I used the following snippet

var paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbwintonView Question on Stackoverflow
Solution 1 - IosBen GottliebView Answer on Stackoverflow
Solution 2 - IosLeeView Answer on Stackoverflow
Solution 3 - IosZelkoView Answer on Stackoverflow
Solution 4 - IosNguyễn Văn ChungView Answer on Stackoverflow
Solution 5 - IosSuresh VelusamyView Answer on Stackoverflow