【发布时间】:2015-01-01 11:33:28
【问题描述】:
我有一个基于沙盒文档的 Mac 应用程序。我的文档包含用户机器上的图像。我想将文档范围的书签保存到文档中使用的图像中,以便在关闭并重新打开文档时可以访问该图像。
这是我创建书签的方法:
//path is path to an image
//for a new document docUrl is set to the location where we will save our document
NSURL * pathUrl = [NSURL fileURLWithPath:path];
NSError * error;
NSData * pathBookmarkData = [pathUrl bookmarkDataWithOptions:
(NSURLBookmarkCreationWithSecurityScope
| NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess)
includingResourceValuesForKeys:[NSArray arrayWithObject:NSURLPathKey]
relativeToURL:docUrl error:&error];
这会导致以下错误:
Error Domain=NSCocoaErrorDomain Code=260 "The file “Untitled.mydocext” couldn’t be opened because there is no such file." (Collection URL points to a file that doesn't exist) UserInfo=0x608000070800 {NSURL=file:///Users/myname/Pictures/Untitled.mydocext, NSDebugDescription=Collection URL points to a file that doesn't exist}
如何创建文档范围的书签以保存到新文档中?
这是我获取路径的方式:
NSArray* fileTypes = [[NSArray alloc] initWithObjects:@"png", @"jpg", @"jpeg", @"bmp", @"gif", @"tif", @"tiff", @"PNG", @"JPG", @"JPEG", @"BMP", @"GIF", @"TIF", @"TIFF", nil];
NSOpenPanel *panel;
panel = [NSOpenPanel openPanel];
[panel setTitle:@"Select Photos"];
[panel setFloatingPanel:YES];
[panel setCanChooseDirectories:YES];
[panel setCanChooseFiles:YES];
[panel setAllowsMultipleSelection:YES];
[panel setAllowedFileTypes:fileTypes];
[panel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
NSMutableArray * pathsArray = [[NSMutableArray alloc] init];
NSArray * urlArray = [panel URLs];
for (NSURL * url in urlArray) {
//this is how I get path to image, assume I am not selecting directories
NSString * path = [url path];
}
}
}];
【问题讨论】:
-
你是如何获得“路径”的?首选方法是使用 NSOpenPanel 获取安全范围的 URL 或用户将图像放入您的应用程序。
-
我延迟获取安全范围的书签,直到用户第一次尝试保存我的文档。这时,我获得了保存文档的位置,因此获得了要在 bookmarkDataWithOptions:includeResourceValuesForKeys:relativeToURL:error: 函数中使用的 relativeURL 来获取文档范围的书签。
-
@AmaltasCoder 你解决过这个问题吗?我正在尝试做同样的事情,但是 OSX 中的各种错误阻止我正确/可靠地保存其中包含文档范围书签的文档。
标签: macos cocoa appstore-sandbox