Borut Tomazin Borut Tomazin - 2 years ago 150
iOS Question

NSFileManager's method createDirectoryAtPath returns false result on iOS

When I try to create a folder using the code bellow it returns NO with an error when I try to create a folder that already exists instead of returning YES:

[[NSFileManager defaultManager] createDirectoryAtPath:[documentsPath stringByAppendingPathComponent:@"temp"] withIntermediateDirectories:NO attributes:nil error:&error];

Apple's documentation says:

Return Value
YES if the directory was created or already exists or NO if an error occurred.

So I should get YES on success or if folder exists. But I get this message when folder exists:

Error Domain=NSCocoaErrorDomain Code=516 "The operation couldn’t be completed. (Cocoa error 516.)" UserInfo=0x200ef5f0 {NSFilePath=/var/mobile/Applications/DA657A0E-785D-49B4-9258-DF9EBAC5D52A/Documents/temp, NSUnderlyingError=0x200ef590 "The operation couldn’t be completed. File exists"}

Is this a bug and should be reported to Apple or am I doing something wrong?

Answer Source

[NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:] will fail if the file exists and it is not a directory.

So the way forward is to not bother creating the directory if it already exists and to throw an exception if it exists and is not a directory:

NSString *filename = [documentsPath stringByAppendingPathComponent:@"temp"];
NSFileManager *fileman = [NSFileManager defaultManager];
BOOL isDir = NO;
if (![fileman fileExistsAtPath:filename isDirectory:&isDir])
    // Create the directory
else if (!isDir)
    NSLog(@"Cannot proceed!");
    // Throw exception
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download