gpt4 book ai didi

objective-c - 目录的安全范围书签

转载 作者:搜寻专家 更新时间:2023-10-30 19:41:01 25 4
gpt4 key购买 nike

我需要为应用程序向该目录写入一些文件的目录提供完全读/写权限。我读到使用沙盒应用程序需要 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 转换。您使用路径进行的所有操作都可以直接使用 URL 完成,只需查看 NSFileManagerNSURL 的文档。唯一可能不明显的是使用 NSURLcheckResourceIsReachableAndReturnError: 而不是 NSFileManagerfileExistsAtPath:,但是请仔细阅读 checkResourceIsReachableAndReturnError: 的文档并采纳其建议。

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

HTH

关于objective-c - 目录的安全范围书签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39051385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com