What is the best way to find the User Documents folder on iPhone?

I read the iPhone Developer Cookbook by Erica Sadun and wonder.

She says in a book that there is a way to find a user document directory with code:

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

but this seems a bit fragile and incompatible with the regular Mac way of doing it:

 NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES); 

Are there any special reasons for using one over the other?

+57
ios objective-c iphone cocoa-touch
Nov 07 '08 at 16:02
source share
5 answers

ObjC:

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

Swift:

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

You will need the first element of the returned array.

+86
Nov 07 '08 at 16:48
source share

Here is the code that I use in my framework.

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; 
+47
Dec 6 '08 at 23:37
source share

You should consider NSFileManager methods that return URLs that are preferred.

 let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL 

This method is designed to search for known and common directories in the system.

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

+13
Oct 11
source share

I use this

 NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *zipLocalPath = [documentPath stringByAppendingString:fileName]; 
0
Jan 17 '15 at 3:25
source share

In swift v3 I used the following snippet

 var paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) 
0
Sep 09 '17 at 11:52 on
source share



All Articles