Reputation: 59
I'm trying to create an app that will copy the selected sound file to the app's directory. To do it, I've written the following code :
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");
}
}
The problems are that I can select each types of files (not only aif, wav, mp3 etc.) and I never get File copied
. Although, the paths are correct. When I delete the if statement, I get an error saying : [NSURL fileSystemRepresentation]: unrecognized selector sent to instance 0x1005a0b90
.
What's wrong in this code?
Upvotes: 1
Views: 705
Reputation: 29886
You're passing an NSURL
to an API that expects a path in an NSString
. You might consider using the URL-based API:
- (BOOL)copyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error NS_AVAILABLE(10_6, 4_0);
Like this:
[fileManager copyItemAtURL: [[openDlg URLs] objectAtIndex:0] toURL: [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]] error:&error];
Also, I'm guessing that the file has already been copied to the bundle since your description indicates that [fileManager fileExistsAtPath:dataPath]
is returning NO
(since your NSLog is never executed.) You can either check that manually, or you can ask the NSFileManager
to delete any existing file before copying in a newly selected file.
Upvotes: 1