Home > DeveloperSection > Forums > Creating a directory in Documents in iOS
Tarun Kumar

Total Post:210

Points:1614
Posted on    August-12-2015 11:18 PM

 iPhone iPhone  Ios  Objective C 
Ratings:


 1 Reply(s)
 401  View(s)
Rate this:

I'm creating a folder in my documents directory and I want to do it without typing out /Users/(username)/Documents/Foo/Bar

 

NSString *directoryPath = [NSString  stringWithFormat:@"%@/Documents/Foo/Bar", NSHomeDirectory()];   

 

BOOL isDir;

NSFileManager *fileManager= [NSFileManager defaultManager];

if(![fileManager fileExistsAtPath:directoryPath isDirectory:&isDir])

    if(![fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:NULL])

        NSLog(@"Error: Create folder failed %@", directoryPath);

 This doesn't work when I try using NSHomeDirectory() with it. But if I typed out the full path /Users/(username)/Documents/Foo/Ba it works. How can it be done to not have to know the users folder?

EDIT: directoryPath becomes

/Users/(username)/Library/Developer/CoreSimulator/Devices/FAB78255-38D2-49BE-9683-7A0676EA2288/data/Containers/Data/Application/67B0AACE-572A-4808-9535-D221AEEB9EFA/Foo/Bar

I just want /Users/(username)



Mikki Halpin
Mikki Halpin

Total Post:23

Points:161
Posted on    August-13-2015 11:45 PM

This is an iOS app. The "Documents" folder of an iOS app's sandbox is not at all related to the user's "Documents" folder on their computer.

Since you appear to be running your iOS in the simulator, the path you are getting is more like what you should be seeing. You do not want a path in the user's home directory.

Keep in mind that you can't get access to the "Documents" folder of an iOS app using NSHomeDirectory(). That may have worked in older versions of iOS but it fails in iOS 8 and later. The proper code needs to be something like this:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,

NSUserDomainMask, YES);

NSString *documentsFolder = paths[0];

NSString *directoryPath = [documentsFolder stringByAppendingPathComponent:

@"Foo/Bar"];


Modified On Aug-13-2015 11:46:33 PM

Don't want to miss updates? Please click the below button!

Follow MindStick