20

I need to retrieve the URL of a resource contained in my Xcode project through a path that begins in the project's directory (aka mainBundle)

So if my specified path if ./snd/archer/acknowledge1.wav, I need to create a URL from that.

I know I can use NSURL(fileURLWithPath:) for system directories, but I don't know how to do this directly from the bundle.

mattgabor
  • 2,064
  • 6
  • 25
  • 38

3 Answers3

32

As of Swift 3, the answer is:

Bundle.main.url(forResource: "acknowledge1", withExtension: "wav", subdirectory: "snd/archer")
luckyhandler
  • 10,651
  • 3
  • 47
  • 64
Guig
  • 9,891
  • 7
  • 64
  • 126
  • 1
    Please fix your answer. Needs comma before 'subdirectory'. This is great answer for Swift 4 (& perhaps Swift 3) – Raymond Naseef Feb 27 '18 at 08:43
  • 2
    In Swift 4 I needed to provide forResource and withExtension only. When I provided the subdirectory it did not find the .webarchive I was loading (which was in a subdirectory). – Alexander Jun 17 '18 at 19:34
22

You would use one of the bundle resourse URL methods

[[NSBundle mainBundle] URLForResource:@"acknowledge1"
                        withExtension:@"wav"
                         subdirectory:@"snd/archer"];

NSBundle.mainBundle().URLForResource("acknowledge1", withExtension:"wav" subdirectory:"snd/archer")

In latest Swift:

Bundle.main.url(forResource: "acknowledge1", withExtension:"wav")
Satyam
  • 15,493
  • 31
  • 131
  • 244
Wain
  • 118,658
  • 15
  • 128
  • 151
1

In Swift 2.3 you'd have to use this unwrapping:

if let resourceUrl = NSBundle.mainBundle().URLForResource("acknowledge1", withExtension: "wav", subdirectory:"snd/archer") {
        if NSFileManager.defaultManager().fileExistsAtPath(resourceUrl.path!) {
            print("file found")
            //do stuff
        }
    }
Async-
  • 3,140
  • 4
  • 27
  • 49