Get resource URL from project specific path

28,805

Solution 1

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")

Solution 2

As of Swift 3, the answer is:

Bundle.main.url(forResource: "acknowledge1", withExtension: "wav", subdirectory: "snd/archer")

Solution 3

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
        }
    }
Share:
28,805
mattgabor
Author by

mattgabor

Undergraduate Computer Science student at UC Davis

Updated on July 05, 2022

Comments

  • mattgabor
    mattgabor almost 2 years

    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.