Get resource URL from project specific path

假装没事ソ 提交于 2019-12-04 10:05:51

问题


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.


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



回答2:


As of Swift 3, the answer is:

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



回答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
        }
    }


来源:https://stackoverflow.com/questions/33591305/get-resource-url-from-project-specific-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!