0

I am trying to create a panel that lets the user choose a path to save a file. When the user selects a directory from the panel that shows relative path (i.e. /folder) the URLs property is contains /folder. When the user selects a directory that shows the full path, URLs property of panel contains the full path (i.e. /User/name/folder). How do I ensure the URLs property will definitely contain the full paths even though the user's panel shows a relative path?

NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setCanChooseFiles:NO];
[panel setCanChooseDirectories:YES];
[panel setAllowsMultipleSelection:NO]; // yes if more than one dir is allowed

NSInteger clicked = [panel runModal];

NSArray<NSURL *> *URLs;
if (clicked == NSFileHandlingPanelOKButton) {
    URLs = [panel URLs];
}
else{
    URLs = [NSArray arrayWithObject:[NSURL URLWithString:[NSString stringWithFormat:@"file://%s/", getenv("HOME")]]];
}
for (NSURL *url in URLs) { // When user clicks cancel, [panel URLs] is empty
    NSString *selectedDirectoryPath = [url.absoluteString substringFromIndex:6];
//  NSString *selectedDirectoryPath = [url path];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *sourceFilePath = [NSString stringWithFormat:@"%@/%@", NSHomeDirectory(), _fileName];
    NSString *destFilePath = [NSString stringWithFormat:@"%@%@", selectedDirectoryPath, _fileName];
}

I thought I could use the path instance property on url, but the array is filled once the user clicks OK to a file path with NSFileHandlingPanelOKButton.

Edit: I found a response that suggests to use beginSheetModalForWindow in NSOpenPanel URL to string , but how do you use this function?

eh1412
  • 43
  • 1
  • 2
  • 8
  • 1
    Have you considered using NSSavePanel? That’s what users expect when saving files. https://developer.apple.com/documentation/appkit/nssavepanel – mahal tertin Jul 27 '22 at 08:02
  • I am looking to allow the user to select a path to where they want to save and it looks like NSSavePanel does not allow that option. https://stackoverflow.com/questions/3396081/how-can-i-use-nssavepanel-to-select-a-directory – eh1412 Jul 28 '22 at 18:20

1 Answers1

0

I used setDirectoryURL to open the panel to the root folder by default. This will help ensure it returns an absolute path, otherwise a relative path is returned.

NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setDirectoryURL:[NSURL URLWithString:[NSString stringWithFormat:@"file:///"]]];
eh1412
  • 43
  • 1
  • 2
  • 8