目录的安全范围书签

Security-Scoped Bookmarks for a directory

我需要为应用程序将某些文件写入该目录的目录授予完全 read/write 权限。我读到使用沙盒应用程序需要 Enable Security-Scoped Bookmark and URL Access 才能在重新启动应用程序后访问文件夹。

所以我尝试根据此处的代码进行一些小修改来实现它What is the correct way to handle stale NSURL bookmarks?

     NSOpenPanel* openDlg = [NSOpenPanel openPanel];
    [openDlg setCanChooseDirectories:YES];
    [openDlg setCanCreateDirectories:YES];
    [openDlg setAllowsMultipleSelection:FALSE];
    if ( [openDlg runModal] == NSOKButton )
    {
        NSArray *files = [openDlg URLs];

        NSString* dirPath =[[files objectAtIndex:0] path];// absoluteString];
        BOOL isDirectory;
        NSFileManager* manager = [NSFileManager defaultManager];



        NSString *Dir = [dirPath stringByAppendingPathComponent:@"ScreenCaptures"];
        if (![manager fileExistsAtPath:Dir isDirectory:&isDirectory] || !isDirectory)
        {
            NSError *error = nil;

            [manager createDirectoryAtPath:Dir
               withIntermediateDirectories:NO
                                attributes:nil
                                     error:&error];
            if (error)
                NSLog(@"Error creating directory snap path: %@", [error localizedDescription]);

        }


            NSURL *url = [NSURL URLWithString:[Dir stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

            NSData *bookmark = nil;
            NSError *error = nil;
            bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
                     includingResourceValuesForKeys:nil
                                      relativeToURL:nil // Make it app-scoped
                                              error:&error];
            if (error) {
                NSLog(@"Error creating bookmark for URL (%@): %@", url, error);
                [NSApp presentError:error];
            }

            NSLog(@"bookmark: %@", bookmark);
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:bookmark forKey:@"bookmark"];

    }

但是上面的代码给我错误

016-08-20 02:19:53.390 FileAccess[635:85753] modalSession has been exited prematurely - check for a reentrant call to endModalSession:
2016-08-20 02:19:59.979 FileAccess[635:85753] Error creating bookmark for URL (/Users/development/Documents/c/ScreenCaptures): Error Domain=NSCocoaErrorDomain Code=262 "Scoped bookmarks can only be made with file URLs" UserInfo={NSURL=/Users/development/Documents/c/ScreenCaptures, NSDebugDescription=Scoped bookmarks can only be made with file URLs}
2016-08-20 02:20:00.021 FileAccess[635:85753] CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme
2016-08-20 02:20:04.967 FileAccess[635:85753] bookmark: (null)

可能是什么问题?上面的代码有什么问题吗?

你的第二条错误消息告诉你出了什么问题 - 你没有使用 file:// URL.

这可以通过从您的路径变量中正确创建 URL 来解决,但是您最好始终坚持使用 URL 而不要执行 URL ->路径 -> URL 转换。您使用路径进行的所有操作都可以直接使用 URLs 完成,只需查看 NSFileManagerNSURL 的文档即可。唯一可能不明显的是使用 NSURLcheckResourceIsReachableAndReturnError: 而不是 NSFileManagerfileExistsAtPath:,但是请仔细阅读 checkResourceIsReachableAndReturnError: 的文档并听取它的建议。

进行这些更改应该至少解决您报告的三个错误。

HTH