Anonymous1
Anonymous1

Reputation: 3907

Objective C - Get file path in subfolder of supporting files

I'm trying to play an mp3 that's in a couple of subfolders:

NSString *fName = @"subfolder1/subfolder2/mp3name";
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:fName ofType: @"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];
myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[myAudioPlayer play];

The mp3 will play if it's not in a subfolder, but it won't play as above in a subfolder. How can I get the mp3 to play from a subfolder?

Upvotes: 0

Views: 967

Answers (2)

Nicolas Miari
Nicolas Miari

Reputation: 16256

When you add resource files as whole folders to your project, Xcode asks you if you want to:

  1. Create Groups
  2. Create Folder references

In the first case, the added folder appears in the project navigator as a yellow folder icon, and all contained files are copied to the root of your app bundle (so file name collisions can occur).

In the second case, the added folder appears in the Project Navigator as a blue folder icon (like the asset catalogs), and the directory structure is respected when the binary is built.

I think in the second case you can use NSBundle's -pathForResource:ofType:inDirectory: to access resources in subdirectories.

Either way, the first argument should be the file name without any intermediate subdirectories (like @DBoyer mentioned in the comments).

Upvotes: 1

Wain
Wain

Reputation: 119041

You need to use a different method so you can specify the path:

- (NSString *)pathForResource:(NSString *)name
                       ofType:(NSString *)extension
                  inDirectory:(NSString *)subpath

Upvotes: 2

Related Questions