I use NSSavePanel only when I deal with text files. If I have an image to export, I use NSOpenPanel so that the user can select a directory, and I don't get caught with in the sandbox file path restriction. This time, though, I want to use NSSavePanel to let the user save an image file (bmp, gif, jpeg, jp2, png).
- (void)exportfile {
NSString *documentFolderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSSavePanel *panel = [NSSavePanel savePanel];
[panel setMessage:@"Please select a path where to save checkboard as an image."]; // Message inside modal window
if ([self fileExists:destinationpath]) {
[panel setDirectoryURL:[NSURL fileURLWithPath:destinationpath]];
} else {
[panel setDirectoryURL:[NSURL fileURLWithPath:documentFolderPath]];
}
//[panel setAllowedFileTypes:[[NSArray alloc] initWithObjects:@"bmp",@"gif",@"jpg",@"jp2",@"png",nil]];
[panel setAllowsOtherFileTypes:YES];
[panel setExtensionHidden:YES];
[panel setCanCreateDirectories:YES];
[panel setNameFieldStringValue:filename];
[panel setTitle:@"Saving checkboard..."]; // Window title
[panel setAccessoryView:accessoryView1];
NSInteger result = [panel runModal];
NSError *error = nil;
if (result == NSOKButton) {
////////////////////////////////////////////
NSString *path0 = [[panel URL] path];
NSMutableString *path1 = [[NSMutableString alloc] initWithString:path0];
if (formatIndex1 == 0) { // formatIndex1 is the index of NSPopMenu
[path1 appendString:@".bmp"];
}
else if (formatIndex1 == 1) {
[path1 appendString:@".gif"];
}
else if (formatIndex1 == 2) {
[path1 appendString:@".jpg"];
}
else if (formatIndex1 == 3) {
[path1 appendString:@".jp2"];
}
else if (formatIndex1 == 4) {
[path1 appendString:@".png"];
}
[self exportfile2:path1]; // <<<<<<<<<<<<<<< Immediate goal
////////////////////////////////////////////
if (error) {
[NSApp presentError:error];
}
}
}
This NSSavePanel has an AccessoryView control, allowing the user to select a graphic format with an NSPopupMenu. Its index is formatIndex1. I know that the code fails if the application is sandboxed. That's because the exact path that the user selects is path0, and the code above appends a file extension to it before reaching exportfile2. So how do I go about getting the exact path with a file extension. Preview automatically appends a file extension if 'Hide extension' is off. Yet, Preview won't fail to export an image.
Thank you for your help.
Try like this below:-