保存文件时出现权限错误(沙盒)

5

我正在尝试将一个文件保存到路径中,在一个沙盒应用程序[OS X]中,但是到目前为止,几乎每次我尝试保存时都会出现错误。这个错误是...

Error saving: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “test.txt” in the folder “Testing”." UserInfo=0x1001f5e70 {NSFilePath=/Users/Seb/Desktop/Testing/test.txt, NSUnderlyingError=0x1001f5d70 "The operation couldn’t be completed. Operation not permitted"}

我已将我的授权中的“用户选择文件”设置为“读/写访问”。
我的代码...
NSString *saveLoc = [NSString stringWithFormat:@"%@/%@.txt",[[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] valueForKey:@"saveURL"]] path],self.theWindow.title];
NSURL *saveURL = [NSURL fileURLWithPath:saveLoc];

NSLog(@"Saving to: %@",saveLoc);

NSError *err = nil;
[self.textView.string writeToURL:saveURL atomically:YES encoding:NSUTF8StringEncoding error:&err];

if (err) {
    NSLog(@"Error saving: %@",err);
    [[NSAlert alertWithError:err] beginSheetModalForWindow:self.theWindow
                                                       modalDelegate:nil
                                                      didEndSelector:NULL
                                                         contextInfo:nil];
}

我做错了什么?我该如何保存文件?

谢谢。

1个回答

10
为了在沙盒外读/写文件,必须获得用户对该文件或其上级目录之一的访问权限。可以使用NSOpenPanelNSSavePanel或拖放来获得访问权限。
应用程序终止后,无法再访问那些文件/目录。
为了永久访问由用户选择的文件/目录,必须使用安全范围书签

看起来我需要一个安全范围的书签,以便永久访问。谢谢! - Seb Jachec
经过一番费力的摸索,以及 http://objcolumnist.com/2012/05/21/security-scoped-file-url-bookmarks/ 的帮助,我终于完美地解决了它。 - Seb Jachec
2
我已经将请求权限和持久化该权限的过程封装在这个类中,如果需要可以使用它。https://github.com/leighmcculloch/AppSandboxFileAccess - Leigh McCulloch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接