I am generating a PDF document and offering the user the option to save it to disk. I present them with an NSSavePanel
for them to select the filename to save it as. If they choose a file that already exists, it prompts them if they are sure and want to Replace that file. If they agree to replace the file, then I generate the PDF and write it to that chosen URL.
However, my write fails with the following error:
CGDataConsumerCreateWithFilename: failed to open `/path/to/.myfile.pdf' for writing: Operation not permitted
I have the appropriate Entitlements to write to files on disk. The file that's in the way is the one I generated during a previous test. Do I need to explicitly delete the existing file before I write mine to that URL or is there some way I can tell the system that it may overwrite the existing file?
This is the code I use to launch the NSSavePanel
(my code saves their last chosen directory so that it can default to the same location for all future saves):
- (NSURL*) requestSaveFilenameForExtension:(NSString*)fileExtension previousSaveDirectorySettingKey:(NSString*)previousDirectorySettingKey defaultFilename:(NSString*)defaultFilename {
NSSavePanel *panel = [NSSavePanel savePanel];
[panel setAllowedFileTypes:[NSArray arrayWithObject:fileExtension]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *previousSaveDirectory = [defaults stringForKey:previousDirectorySettingKey];
if (previousSaveDirectory == nil) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
previousSaveDirectory = [paths objectAtIndex:0];
}
[panel setExtensionHidden:NO];
[panel setNameFieldStringValue:defaultFilename];
[panel setDirectoryURL:[NSURL fileURLWithPath:previousSaveDirectory]];
NSInteger ret = [panel runModal];
if (ret == NSFileHandlingPanelOKButton) {
NSString *saveDirectory = [[[panel URL] absoluteString] stringByDeletingLastPathComponent];
[defaults setValue:saveDirectory forKey:previousDirectorySettingKey];
return [panel URL];
} else {
return nil;
}
}
and here is the code I'm using to write the file to that given URL, it's just standard PDFKit -writeToURL:
:
PDFDocument *document = [self generateDocument];
[document writeToURL:documentURL];