CREATING A DIRECTORY IN DOCUMENTS IN IOS

Tarun Kumar

Total Post:214

Points:1642
Posted by  Tarun Kumar
 672  View(s)
Ratings:
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)

  1. Mikki Halpin

    Post:23

    Points:161
    Re: Creating a directory in Documents in iOS

    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!