macOS 上使用NSFileManager移除文件失败。Operation not permitted

2,672 阅读1分钟

代码如下:

   NSString *tmpFile = [_projectPath stringByAppendingFormat:@"text.txt"];
    NSError *err;
    if ([[NSFileManager defaultManager] fileExistsAtPath:tmpFile]) {
        [[NSFileManager defaultManager] removeItemAtPath:tmpFile error:&err];
    }
    

后面打印出err

Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “TestDir” in the folder “Desktop”." UserInfo={NSFilePath=/Users/sj/Library/Containers/com.user.TestSync/Data/Desktop/TestDir, NSUnderlyingError=0x60400044cc60 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"

找了好久,好多答案都没回答到点上。折腾了半天,在stackoverflow上看到了答案

That is because your macOS Application is running in the "App Sandbox", check your "Capabilities" tab in the target settings.

这里大概的意思久是你的应用程序跑在沙盒上。检查你工程目标 `Capabilities`设置

根据你的情况你可以
1、禁用沙河模式
2、让用户通过打开“打开”对话框来选择文件夹
3、在其他受保护的用户文件夹(例如下载等)中启用读/写
4、或者直接在您的主目录中创建TestDir,而无需使用任何软链接文件夹

后面还提到了调起访达窗口,还要这样设置(ps:这个我没测试过,因为我代码是这样写的)

NSOpenPanel.canCreateDirectories to true: