我正在尝试创建一个将所选声音文件复制到应用程序目录的应用程序。为此,我编写了以下代码:
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setAllowsMultipleSelection:NO];
[openDlg setCanChooseDirectories:NO];
[openDlg setAllowedFileTypes:[NSArray arrayWithObjects:@"aif",@"aiff",@"mp3",@"wav",@"m4a",nil]];
if ( [openDlg runModalForDirectory:nil file:nil] == NSOKButton )
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dataPath = [[NSBundle mainBundle] bundlePath];
NSLog(@"Datapath is %@", dataPath);
NSLog(@"Selected Files : %@",[[openDlg URLs] objectAtIndex:0]);
if ([fileManager fileExistsAtPath:dataPath] == NO)
{
[fileManager copyItemAtPath:[[openDlg URLs] objectAtIndex:0] toPath:[[NSBundle mainBundle] bundlePath] error:&error];
NSLog(@"File copied");
}
}
问题是我可以选择每种类型的文件(不仅仅是aif,wav,mp3等)而且我永远不会得到File copied
。虽然,路径是正确的。当我删除if语句时,我收到一条错误消息:[NSURL fileSystemRepresentation]: unrecognized selector sent to instance 0x1005a0b90
。
这段代码有什么问题?
答案 0 :(得分:1)
您正在将NSURL
传递给期望NSString
中的路径的API。您可以考虑使用基于URL的API:
- (BOOL)copyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error NS_AVAILABLE(10_6, 4_0);
像这样:
[fileManager copyItemAtURL: [[openDlg URLs] objectAtIndex:0] toURL: [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]] error:&error];
另外,我猜这个文件已经被复制到了包中,因为你的描述表明[fileManager fileExistsAtPath:dataPath]
正在返回NO
(因为你的NSLog永远不会执行。)你可以检查一下手动,或者您可以要求NSFileManager
删除任何现有文件,然后再复制新选择的文件。