我正在尝试将NSURL
转换为NSString
以在我的程序中的其他地方使用。
这是我的代码:
- (IBAction)openExistingDocument:(id)sender {
NSOpenPanel* panel = [NSOpenPanel openPanel];
[panel setCanChooseDirectories:NO];
[panel setAllowsMultipleSelection:NO];
[panel setMessage:@"Please select a File or Folder containing your character's .png layers"];
[panel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
NSURL* theDoc = [[panel URLs] objectAtIndex:0];
NSString* unformattedURL = [NSString stringWithContentsOfURL:theDoc encoding:NSASCIIStringEncoding error:NULL];
NSString * formattedURL = [unformattedURL stringByReplacingOccurrencesOfString:@"file:/" withString:@""];
NSLog(@"the url says:%@", theDoc);
NSLog(@"the unformatted string says: %@", unformattedURL);
NSLog(@"the formatted string says: %@", formattedURL);
}
}];
}
当我运行程序时,这是我的命令行输出的内容:
2012-01-29 18:43:19.205 Cocos2dCharacterRigger[516:407] the url says:file://localhost/Users/*****/Desktop/mockupsite.jpg
2012-01-29 18:43:19.213 Cocos2dCharacterRigger[516:407] the unformatted string says: ÿØÿá.]Exif
2012-01-29 18:43:19.219 Cocos2dCharacterRigger[516:407] the formatted string says: ÿØÿá.]Exif
有人可以指出我做错了什么吗?
答案 0 :(得分:6)
您正在将URL中文件的内容加载到字符串中。您正在将文件作为ASCII字符串加载(该文件几乎肯定不是 - 它是图像)并且您忽略了任何错误。
要获取网址的实际路径,请向网址发送-path
消息。所以,要获得一个包含路径的字符串:
NSString* filePath = [theDoc path];
NSLog(@"the url: %@", theDoc);
NSLog(@"the path: %@", filePath);
这应打印以下内容(基于您上面的日志):
the url: file://localhost/Users/*****/Desktop/mockupsite.jpg
the file: /Users/*****/Desktop/mockupsite.jpg