I’m having some problems trying to create a folder using NSFileManager in MacOS X. I’m creating the software in Lion if that changes anything.
Anyway. The program structure is something like this:
- Fill in some fields.
- Choose a folder using NSOpenPanel.
- The program generates the name of the new folder from the fields.
- Create a folder with that name in the chosen folder.
The code that is supposed to create the folder looks like this:
NSString *name = [pnameField stringValue];
NSString *number = [self parseVerknr:[pnumberField stringValue]];
NSString *date = [pdateField stringValue];
NSString *folderName;
//Here I generate the folder name from some rules and stuffsies
//It ends up as something like: 13245_08 - cp. - name
NSOpenPanel *myPanel = [NSOpenPanel openPanel];
myPanel.canChooseFiles = NO;
myPanel.canChooseDirectories = YES;
myPanel.canCreateDirectories = YES;
[myPanel beginWithCompletionHandler:^(NSInteger result){
if (result==NSFileHandlingPanelOKButton){
NSFileManager *myManager = [[NSFileManager alloc] init];
NSError *merror;
NSString *directoryString = [NSString stringWithFormat:@"%@%@", [myPanel.URL absoluteString], folderName];
//Here the directory string looks like file://localhost/Users/username/Documents/folders/12345_09 - cp. - Koop
directoryString = [directoryString substringFromIndex:6];
//After it looks like: /localhost/Users/username/Documents/folders/12345_09 - cp. - Koop
NSLog(@"directory: %@", directoryString);
[myManager createDirectoryAtPath:directoryString withIntermediateDirectories:YES attributes:nil error:&merror];
NSLog(@"%@", [merror localizedDescription] );
}
}];
If I don’t take the substring from index 6 I get a large error stack (tried to take it from 16 too which did the same). If I use the split string I get the following error:
You don’t have permission to save the file “localhost” in the folder “PK Bear”.
Since PK Bear is the name of my “hard drive” I’m guessing the program needs to get permission to access the hard drive. I just have no idea how to do this.
Any help would be greatly appreciated.
The problem is the way you’re creating the path string. In particular,
-[NSURL absoluteString]returns a string representation of the URL, not a filepath string. You should use NSURL and NSString’s methods for working with paths. As explained in the documentation,-[NSURL path]returns a path string suitable for inputting into NSFileManager methods.Try this: