Alex G Alex G - 3 months ago 18
iOS Question

Create directory programmatically

I want to create a directory inside my applicationSupportDirectory. My understanding is that the applicationSupportDirectory does not allow users to see the data within. This is why I have chosen it. However, the code I am using below seems to fail and I am not sure why.

Can anyone tell me what I have done wrong? Thanks!

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationDirectory = [paths objectAtIndex:0]; // Get directory
NSString *dataPath = [applicationDirectory stringByAppendingPathComponent:@"drawings"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){

NSError* error;
if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
;// success
else
{
NSLog(@"Failed");
}
}
}

Answer
NSString *directoryName = @"drawing";

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,   NSUserDomainMask, YES);

NSString *applicationDirectory = [paths objectAtIndex:0];
NSString *filePathAndDirectory = [applicationDirectory stringByAppendingPathComponent:directoryName];
NSError *error;

if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
                               withIntermediateDirectories:YES
                                                attributes:nil
                                                     error:&error])
{
    NSLog(@"Create directory error: %@", error);
}

Hope it will help you