Using url returned from NSOpenPanel to save multiple files

I am trying to allow the user to save a set of files (generated from my app) into a folder chosen by the user via the NSOpenPanel API, but am constantly getting errors that the end URL (with the folder URL and appended file name) cannot be written to.

I am not doing this across app sessions, so I can see why I should need Security Scope management, but I have been trying that and am just not sure where it should be used, if so.

On previous os versions it seems I could have simply appended my file name and write the file. I haven't found any examples of how this should be done anywhere that are recent.

Here is what I am currently doing:

URLList contains list of temporary file URLs.

Code Block obj-c
    NSOpenPanel * openPanel = NSOpenPanel.openPanel;
    openPanel.prompt = MVNLocalizedString(@"SAVE");
    openPanel.canCreateDirectories = YES;
    openPanel.canChooseFiles = NO;
    openPanel.canChooseDirectories = YES;
    openPanel.allowsMultipleSelection = NO;
    [openPanel beginSheetModalForWindow:self.view.window completionHandler:^(NSModalResponse result) {
        if ((result == NSModalResponseOK) && openPanel.URL) {
            NSURL * locationURL = openPanel.URL;
            BOOL accessed = [locationURL startAccessingSecurityScopedResource];
            NSFileManager * manager = [NSFileManager new];
            for (NSURL * aURL in URLList) {
                NSURL * newFileURL = [locationURL URLByAppendingPathComponent:aURL.lastPathComponent];
                NSError * error = nil;
                if (![manager copyItemAtURL:aURL toURL:newFileURL error:&error]) {
                    NSLog(@"There was an error saving a file: %@", error);
                }
            }
            [locationURL stopAccessingSecurityScopedResource];
        }
    }];

My calling of the startAccessingSecurityScopedResource is me attempting to make that work, but doesn't seem correct to me. It doesn't work with or without that though.

Can anyone tell me what I am doing wrong here?

Thanks,
Scott

Accepted Reply

So I wanted to let anyone know that I figure this out because I have not seen this info anywhere else. In a Sandboxed app, the entitlements, the default config for the File Access has the "User Selected File" set to "Read Only". Changing this to "Read/Write" allowed me to just use the URL directly and append a file name and write to it, without having to use the Scoped stuff at all, which is how it should be.

Replies

So I wanted to let anyone know that I figure this out because I have not seen this info anywhere else. In a Sandboxed app, the entitlements, the default config for the File Access has the "User Selected File" set to "Read Only". Changing this to "Read/Write" allowed me to just use the URL directly and append a file name and write to it, without having to use the Scoped stuff at all, which is how it should be.