我想用NSOpenpPanel打开myfile.plist但是如果用户刚刚选择了plist,我也会访问myfile.png。我已经尝试访问png了
NSString* url = [[NSString stringWithFormat:@"file://localhost%@%@%@", pathWithoutFilename, @"/", imageFileName ]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
但正在做:
NSData* imageData = [[NSData alloc] initWithContentsOfURL:nsurl];
NSImage *sourceImage = [[NSImage alloc] initWithData:imageData];
NSImage是零。
我怎么样?
答案 0 :(得分:0)
使用NSURLBookmarkCreationWithSecurityScope为Sandbox Cocoa应用程序提供正确的保存和Retreive书签技巧: 最后
-(void)saveTheNSData:(NSData *)data withFileName:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
[data writeToFile:filePath atomically:NO];
}
-(NSURL*) getNSURLFromBookmarkIfExists:(NSString*) filename forType:(NSString*) type
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:filename];
NSData* data = [[NSData alloc] initWithContentsOfFile: filePath];
if(data != nil)
{
NSURL* outUrl = [NSURL URLByResolvingBookmarkData:[[NSUserDefaults standardUserDefaults] objectForKey:type] options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:nil error:nil];
[outUrl startAccessingSecurityScopedResource];
return outUrl;
}
else
return nil;
}
另外请查看此示例,了解使用 [NSUserDefaults standardUserDefaults] 设置书签的正确方法:
-(void) savePlistWithPlistUrl:(NSURL*) plistUrl andImageUrl:(NSURL*) imageUrl
{
NSData *bookmarkPlist = [self bookmarkFromURL:plistUrl];
NSArray* pathSplitted = [pathFilePlist pathComponents];
NSString* filenamePlist = [pathSplitted objectAtIndex:[pathSplitted count]-1];
NSData *bookmarkImage = [self bookmarkFromURL:imageUrl];
NSArray* pathImageSplitted = [imageUrl pathComponents];
NSString* filenameImage = [pathImageSplitted objectAtIndex:[pathImageSplitted count]-1];
NSUserDefaults* prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:bookmarkPlist forKey:@"ExportPlist"];
[prefs setObject:bookmarkImage forKey:@"ExportImage"];
[prefs synchronize];
// save the data bookmark
[self saveTheNSData: bookmarkPlist withFileName:filenamePlist];
[self saveTheNSData: bookmarkImage withFileName:filenameImage];
}